Java Swing : why must resize frame, so that can show components have added(Java Swing:为什么必须调整框架大小,这样才能显示组件已添加)
问题描述
我有一个简单的 Swing GUI.(不仅如此,我写的所有摇摆GUI).运行它时,除了空白屏幕,它什么都不显示,直到我调整主框架的大小,所以每个组件都重新绘制,我可以显示它们.
I have a simple Swing GUI. (and not only this, all swing GUI I have written). When run it, it doesn't show anything except blank screen, until I resize the main frame, so every components have painted again, and I can show them.
这是我的简单代码:
public static void main(String[] args) {
JFrame frame = new JFrame("JScroll Pane Test");
frame.setVisible(true);
frame.setSize(new Dimension(800, 600));
JTextArea txtNotes = new JTextArea();
txtNotes.setText("Hello World");
JScrollPane scrollPane = new JScrollPane(txtNotes);
frame.add(scrollPane);
}
所以,我的问题是:当我开始这个课程时,框架会出现我添加的所有组件,直到我调整框架大小.
So, my question is : how can when I start this class, the frame will appear all components I have added, not until I resize frame.
谢谢:)
推荐答案
JFrame可见后不要向JFrame添加组件(setVisible(true))Do not add components to
JFrameafter theJFrameis visible (setVisible(true))在框架上调用
setSize()而不是调用pack()并不是很好的做法(导致JFrame的大小调整为适合其子组件的首选大小和布局)并让LayoutManager处理大小.Not really good practice to call
setSize()on frame rather callpack()(CausesJFrameto be sized to fit the preferred size and layouts of its subcomponents) and letLayoutManagerhandle the size.使用 EDT (Event-Dispatch-线程)
Use EDT (Event-Dispatch-Thread)
调用
JFrame#setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)正如@Gilbert Le Blanc(对他 +1)所说,否则即使在之后,您的 EDT/Initial 线程仍将保持活动状态JFrame已关闭call
JFrame#setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)as said by @Gilbert Le Blanc (+1 to him) or else your EDT/Initial thread will remain active even afterJFramehas been closed像这样:
public static void main(String[] args) { //Create GUI on EDT Thread SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("JScroll Pane Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextArea txtNotes = new JTextArea(); txtNotes.setText("Hello World"); JScrollPane scrollPane = new JScrollPane(txtNotes); frame.add(scrollPane);//add components frame.pack(); frame.setVisible(true);//show (after adding components) } }); }这篇关于Java Swing:为什么必须调整框架大小,这样才能显示组件已添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Swing:为什么必须调整框架大小,这样才能显示组件已添加
- 获取数字的最后一位 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
