Java布局不显示组件(有时)
我正在为我的学生写一个数学测验,包括用于渲染的JLatexMath和用于蜂鸣器的jinput。问题是,有时(像每四次一样)当我启动程序时,没有一个组件是可见的。它们在调整JFrame的大小后出现。 首先,我想到了jinput或jlatexMath库中的bug,但即使代码很小,我也会遇到同样的错误:Java布局不显示组件(有时),java,swing,components,boxlayout,Java,Swing,Components,Boxlayout,我正在为我的学生写一个数学测验,包括用于渲染的JLatexMath和用于蜂鸣器的jinput。问题是,有时(像每四次一样)当我启动程序时,没有一个组件是可见的。它们在调整JFrame的大小后出现。 首先,我想到了jinput或jlatexMath库中的bug,但即使代码很小,我也会遇到同样的错误: public class Shell extends JFrame{ private JButton button1; private JButton button2; private
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,有关更多详细信息,请参见如果您在Swing方面遇到奇怪的问题,最好注意文档并确保从那里开始。好的,thx获得快速答案。当我添加System.out.println(javax.swing.SwingUtilities.isEventDispatchThread())时;对于构造函数,我在控制台上得到false。如何将我的线程设置为EventDispatchThread?我给你的链接左侧有几个链接。最好阅读所有文档,否则谁知道你错过了什么。但是您确实需要阅读关于Java并发性的整个章节。至少。是的,我注意到了链接:-)我已经发现,JFrame的创建应该是这样的:SwingUtilities.invokeLater(new Runnable(){public void run(){new Shell();});但我会继续阅读…到目前为止,构造函数末尾的setVisible似乎工作得很好。谢谢你的帮助:-)