Java布局不显示组件(有时) [英] Java Layout not showing components (sometimes)
问题描述
我正在为我的学生写一个MathQuiz,包括用于渲染的JLatexMath和用于蜂鸣器的jinput。问题是,当我启动程序时,有时(就像每四次一样),没有任何组件可见。它们在调整JFrame大小后出现。
首先我在考虑jinput或jlatexMath库中的Bugs,但即使使用这个最小代码我也会得到相同的错误:
I'm writing a MathQuiz for my pupils including JLatexMath for rendering and jinput for the buzzers. The problem is, that sometimes (like every fourth time) when I start the program, none of the components are visible. They appear after resizing the JFrame. First I was thinking of Bugs in the jinput or jlatexMath libraries, but I do get the same Error even with this minimal Code:
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);
移至构造函数的末尾。
Start by moving setVisible(true);
to the end of the constructor.
而不是在这里......
Instead of been here...
public Shell() {
super("blaBla");
this.setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//...
}
将它移到这里......
Move it here...
public Shell() {
super("blaBla");
//...
add(Box.createVerticalStrut(20));
add(formulaPanel);
setVisible(true);
}
为了防止任何其他可能的图形故障,你应该始终从你的UI开始在事件调度线程中,请参阅初始线程以获取更多详细信息
To protect against any other possible graphical glitches, you should always start you UI's from within the Event Dispatching Thread, see Initial Threads for more details
这篇关于Java布局不显示组件(有时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!