2015-10-16 86 views
-3

为什么JButton不出现?按钮未添加到jframe

package expt; 

import java.awt.Graphics; 

import javax.swing.*; 

class th extends JFrame 
{ 
    JButton b=new JButton("Click"); 

    th() 
    { 
     setVisible(true); 

     setSize(800, 400); 

     setResizable(false); 

     setDefaultCloseOperation(this.EXIT_ON_CLOSE); 

     setLayout(null); 

     getContentPane().add(b); 

    } 

    public void paint(Graphics g) 
    { 
     g.drawString("welcome", 150, 50); 
    } 

    public static void main(String args[]) 
    { 
     new th(); 
    } 
} 
+0

有什么问题吗? –

+0

调用'rePaint();' – R9J

回答

1

make'setVisible(true)'是您最后一次声明的方法。

工作代码:

th(){ 

    setDefaultCloseOperation(this.EXIT_ON_CLOSE); 
    setLayout(null); 
    setSize(800, 400); 
    setResizable(false); 


    b.setSize(200, 100); //Those line 
    b.setLocation(30, 60); //needed as using setLayout(null) 
    //b.setBounds(30, 60, 200, 100); //Or only this method 
    getContentPane().add(b); 

    setVisible(true); 

} 

当您使用setLayout(null)应手动固定大小和按键的位置。

尽量避免空布局

了解布局https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html