将setVisible()函数放在函数的开头是不同的当我把它放在函数的末尾?

Lin*_*Rom 1 java jframe

我只是Java GUI编程的新手,我遇到的问题是,当我将setVisible()函数放在构造函数调用的函数的开头时,我的面板中的组件会丢失,但是当它在最后时它工作正常.见下面的代码:

public static void main(String[] args) 
{
    new MainClass();
}

public MainClass()
{ 
    setFrame();
}

private void setFrame()
{
    JFrame frame = new JFrame();

    frame.setSize(400,400);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   // Some area where the object of my components inside the panel is created and initialized.
   // If I just place a label and a button, it will appear on the panel. However if I add the JTextArea, all the components in my panel is gone. Just like the code below.

    textArea1 = new JTextArea(20,34);
    textArea1.setWrapStyleWord(true);
    textArea1.setLineWrap(true);
    JScrollPane scroll = 
            new JScrollPane(textArea1, 
                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    panel.add(scroll);
    frame.add(panel);
    // Works fine when setVisible(true); it placed here.
}
Run Code Online (Sandbox Code Playgroud)

关于将setVisible()函数放置到方法的开头或结尾可能会出现什么问题.

Mar*_*o13 5

正如评论和其他答案中已经指出的那样:

setVisible(true)添加完所有组件后,最后应调用.


这并不直接回答您的问题.你的问题的答案是:是的,它有所作为.如果setVisible在添加所有组件之前调用,在某些情况下,它可能适用于某些程序,某些PC,某些Java版本以及某些操作系统 - 但您总是希望它可能无法正常工作一些案例.

您将在stackoverflow和其他地方找到许多相关问题.这些问题的常见症状是某些组件未正确显示,然后在调整窗口大小时突然出现.(调整窗口大小基本上会触发布局和重新绘制).


当您违反Swing的线程规则时,意外行为的可能性会增加.而且,从某种意义上说,你确实违反了Swing的线程规则:你应该总是在Event Dispatch Thread上创建GUI!

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SomeSwingGUI
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    // This method may (and will) only be called
    // on the Event Dispatch Thread
    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();

        // Add your components here        

        f.setVisible(true); // Do this last
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下:Timothy Truckle在评论中指出你不应该setVisible从构造函数中调用.这是真的.更重要的是:您通常应该直接创建一个类extends JFrame.(在某些(罕见!)情况下,这是合适的,但一般准则应该是延伸JFrame)