Java Swing:为什么必须调整框架大小,以便可以显示已添加的组件 [英] Java Swing : why must resize frame, so that can show components have added

查看:87
本文介绍了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 c>可见( setVisible(true)

    调用<$ c不是很好的做法$ c> setSize()在帧而不是调用 pack()(导致 JFrame 到大小适合其子组件的首选大小和布局)并让 LayoutManager 处理大小。

    Not really good practice to call setSize() on frame rather call pack() (Causes JFrame to be sized to fit the preferred size and layouts of its subcomponents) and let LayoutManager handle the size.

    使用 EDT (Event-Dispatch-Thread)

    Use EDT (Event-Dispatch-Thread)

    调用 JFrame #setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)如@Gilbert Le Blanc所述(+1给他)或者你的EDT /初始线程将保持活跃前夕n 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 after JFrame has 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:为什么必须调整框架大小,以便可以显示已添加的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆