Java Layout not showing components (sometimes)(Java 布局不显示组件(有时))
问题描述
我正在为我的学生编写一个 MathQuiz,包括用于渲染的 JLatexMath 和用于蜂鸣器的 jinput.问题是,有时(比如每四次)当我启动程序时,没有一个组件是可见的.它们在调整 JFrame 大小后出现.首先,我在考虑 jinput 或 jlatexMath 库中的错误,但即使使用这个最小的代码,我也会得到相同的错误:
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);
//...
}
把它移到这里...
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 布局不显示组件(有时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 布局不显示组件(有时)


基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01