1

在创建 JFrame 并添加一些组件时,我注意到如果在设置 JFrame 可见和添加按钮之间创建 JComboBox 的实例,则按钮会消失。

我首先创建一个 JFrame:

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);

然后我添加设置可见的框架并添加一个 JButton:

frame.setVisible(true);
frame.add(new JButton("text"));

它按预期工作并显示一个大按钮:

带有按钮的 JFrame

但是,如果我在这些行之间创建一个 JComboBox 实例:

frame.setVisible(true);
new JComboBox();
frame.add(new JButton("text"));

现在按钮不见了..

没有按钮的 JFrame

我希望没有任何变化,因为我只是创建一个实例而不将它分配给任何东西。
为什么按钮会消失?

此外,如果移到new JComboBox();上方frame.setVisible(true);,按钮将再次可见。

4

3 回答 3

3

Once you display the UI, it should not be modified from any thread except of the EDT. In the first case you had some "luck", and it worked. In the second case probably the time of creation of the JComboBox was long enough to prevent you from modifying the UI from a thread that is not the EDT.

What you should do, is invoking that code on the EDT:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.add(new JButton("text"));
        frame.setVisible(true);
    }
})
于 2012-11-05T11:07:17.860 回答
1

我发现问题出在setSize();setVisible(true);JFrame. 所以答案很简单,调用setSize();setVisible(true)在代码末尾(或者更好的是,调用pack();而不是setSize()),一切都应该正常工作:

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;


public class Fnatte {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        new JComboBox();
        frame.add(new JButton("Text"));
        //frame.setSize(200,200);
        frame.pack();
        frame.setVisible(true);
    }
}
于 2012-11-05T11:20:00.993 回答
0

来自 add() 方法的 JavaDoc:

If the container has already been
displayed, the hierarchy must be 
validated thereafter in order to
display the added component.

改变:

frame.setVisible(true);
new JComboBox();
frame.add(new JButton("text"));

至:

frame.setVisible(true);
new JComboBox();
frame.add(new JButton("text"));
frame.validate();

我认为您遇到的奇怪之处与其说是“new JComboBox();”的添加。但事实上调用“frame.add(new JButton("text"));” 在调用“frame.setVisible(true);”之后 无需调用“frame.validate();”即可工作。

于 2012-11-05T11:28:41.793 回答