gpt4 book ai didi

java - 扩展 JPanel 的类不会更新 UI

转载 作者:行者123 更新时间:2023-12-01 21:44:33 25 4
gpt4 key购买 nike

我有两个类:一个扩展了 JFrame (MyFrame),另一个扩展了 JPanel (MyPanel) )。这个想法是能够将 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();
}
}

代码运行并且不会出错,但将 MyPanel 添加到 MyFrame 时 UI 未更新。

最佳答案

与与类似问题相关的所有其他问题一样,将 setVisible(true); 移至构造函数的末尾。

类似...

public class MyFrame extends JFrame {

public MyFrame() {
JPanel panel = new MyPanel();
add(panel);
pack();
setVisible(true);
}
}

Swing 布局是惰性的,它们不会更新,除非您告诉它们(或其他一些操作,例如发生调整大小/重新显示的顶级容器)

您还应该使用 pack 根据窗口内容的大小要求为窗口指定初始大小。

话虽如此,您确实应该避免从像 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);
}
});
}

关于java - 扩展 JPanel 的类不会更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36095398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com