我是 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.
}
关于将 setVisible()
函数放在方法的开头或结尾可能会出现什么问题。
最佳答案
正如评论和其他答案中已经指出的那样:
您应该在添加完所有组件后调用 setVisible(true)
。
这并没有直接回答您的问题。您的问题的答案是:是的,它会有所作为。如果在添加所有组件之前调用 setVisible
,它可能在某些情况下适用于某些程序、某些 PC、某些 Java 版本和某些操作系统- 但您总是必须预料到它在某些情况下可能无法按预期工作。
您会在 stackoverflow 和其他地方找到许多相关问题。这些问题的通常症状是某些组件无法正常显示,然后在调整窗口大小时突然出现。 (调整窗口大小基本上会触发布局和重绘)。
当您违反 Swing 的线程规则时,意外行为的可能性会增加。而且,在某种意义上,您确实违反了 Swing 的线程规则:您应该始终在事件调度线程上创建 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
}
}
顺便说一句:Timothy Truckle 在评论中指出,您不应从构造函数中调用 setVisible
。这是真实的。更重要的是:您通常应该不直接创建扩展JFrame
的类。 (在某些(罕见!)情况下,这是合适的,但一般准则应该是不扩展 JFrame
)
关于java - 将 setVisible() 函数放在函数的开头是否与我将它放在该函数的末尾有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40092281/