我正在使用一本书来学习java。我已经创建了一个Swing窗口但是当我尝试创建JButton时,它们在运行时不可见。我已经完全按照原样复制了代码,但它仍然不可见。这是代码:
import javax.swing.*;
class Buttons extends JFrame
{
JPanel pnl = new JPanel();
public Buttons()
{
super("Swing Window");
setSize(500,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
setVisible(true);
pnl.add(new JButton("Click Me"));
}
public static void main(String[] args)
{
Window gui = new Window();
}
}
答案 0 :(得分:6)
变化:
setVisible(true);
pnl.add(new JButton("Click Me"));
要:
pnl.add(new JButton("Click Me"));
pack(); // very important!
setVisible(true); // should be last!
答案 1 :(得分:-1)
将窗口更改为按钮,它工作正常!!!
import javax.swing.*;
class Buttons extends JFrame
{
JPanel pnl = new JPanel();
public Buttons()
{
super("Swing Window");
setSize(500,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
setVisible(true);
pnl.add(new JButton("Click Me"));
}
public static void main(String[] args)
{
Buttons gui = new Buttons();
}
}