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 布局不显示组件(有时)


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01