我正在为我的学生编写 MathQuiz,包括用于渲染的 JLatexMath 和用于蜂鸣器的 jinput。问题是,有时(比如每四次)当我启动程序时,没有任何组件是可见的。它们在调整 JFrame 的大小后出现。 首先,我想到了 jinput 或 jlatexMath 库中的错误,但即使使用这个最小的代码,我也确实遇到了同样的错误:
public class Shell extends JFrame{
private JButton button1;
private JButton button2;
private Formula formula;
public Shell() {
super("blaBla");
this.setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
Box b = Box.createHorizontalBox();
button1 = new JButton(" ");
button1.setEnabled(false);
b.add(button1);
b.add(Box.createHorizontalGlue());
button2 = new JButton(" ");
button2.setEnabled(false);
b.add(button2);
add(b);
JPanel formulaPanel = new JPanel();
add(Box.createVerticalStrut(20));
add(formulaPanel);
}
public static void main(String[] args) {
Shell s = new Shell();
}
}
代码有什么问题?
最佳答案
首先将 setVisible(true);
移动到构造函数的末尾。
而不是在这里...
public Shell() {
super("blaBla");
this.setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//...
}
把它移到这里...
public Shell() {
super("blaBla");
//...
add(Box.createVerticalStrut(20));
add(formulaPanel);
setVisible(true);
}
为了防止任何其他可能的图形故障,您应该始终从事件调度线程中启动您的 UI,请参阅 Initial Threads了解更多详情
关于Java 布局不显示组件(有时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665955/