[英]Class extending JPanel doesn't update UI
I have two classes: one which extends JFrame
( MyFrame
) and one which extends JPanel
( MyPanel
). 我有两个类:一类扩展
JFrame
( MyFrame
)和一类扩展JPanel
( MyPanel
)。 The idea is to be able to add an instance of the MyPanel
class to an existing, visible instance of MyFrame
. 我们的想法是能够将一个实例添加
MyPanel
类的现有的,可见的实例MyFrame
。
public class MyFrame extends JFrame {
public MyFrame () {
setVisible(true);
JPanel panel = new MyPanel();
add(panel);
}
}
public class MyPanel extends JPanel {
public MyPanel () {
add(new JButton("Test"));
}
}
public class Program {
public static void main (String[] args) {
new MyFrame();
}
}
The code runs and doesn't error, but the UI isn't updated when MyPanel is added to MyFrame. 代码会运行并且不会出错,但是将MyPanel添加到MyFrame时不会更新UI。
Like all the other questions relating to similar issues, move setVisible(true);
像其他所有与类似问题有关的问题一样,移动
setVisible(true);
to the end of the constructor. 到构造函数的末尾。
Something like... 就像是...
public class MyFrame extends JFrame {
public MyFrame() {
JPanel panel = new MyPanel();
add(panel);
pack();
setVisible(true);
}
}
Swing layouts are lazy, they won't update until you tell them to (or some other action, like the top level container been resized/reshown occurs) Swing布局是惰性的,它们不会更新,直到您告知它们为止(或发生其他操作,例如发生了已调整大小/重新显示顶级容器的情况)
You should also use pack
to give your window a initial size, base on the size requirements of its content. 您还应该使用
pack
根据窗口内容的大小要求为其指定初始大小。
Having said all that, you really should avoid extending from top level containers like JFrame
, lets face it, you're not really adding any new functionality to the class and instead, simply create a new instance when you need it... 说了这么多,您真的应该避免从像
JFrame
这样的顶级容器扩展,让我们面对JFrame
,您并没有真正在类中添加任何新功能,而是仅在需要时创建一个新实例。
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MyPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.