[英]Swing JComboBox weird behavior
I observe the following behavior (on the Windows 7 platform) : 我观察到以下行为(在Windows 7平台上):
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame{
JPanel p;
JComboBox<String> l;
JLabel title;
public static void main(String[] arg){
Main m = new Main();
m.setVisible(true);
m.setSize(400,400);
m.p = new JPanel();
//m.l = new JComboBox<String>();
m.title = new JLabel("HELLO");
m.p.add(m.title);
m.setContentPane(m.p);
}
}
Displays HELLO
, but if I uncomment the line that instantiates the JComboBox
, it won't display anything. 显示
HELLO
,但如果我取消注释实例化JComboBox
的行,它将不会显示任何内容。 What could cause that? 可能导致什么? Are you able to reproduce the bug?
你能重现这个bug吗?
Solution from my comment: 我的评论解决方案:
Move
m.setVisible(true);
移动
m.setVisible(true);
at the end.在末尾。
Another comment from Jens Schauder : Jens Schauder的另一条评论:
Your code should also run in the EDT.
您的代码也应该在EDT中运行。 Anything else is asking for trouble
别的什么都在惹麻烦
May be he wants to tell something like this: 也许他想说出这样的话:
Everything dealing with Swing components, including there construction must run in the EDT . 处理Swing组件的所有事情,包括那里的构造都必须在EDT中运行 。 If it doesn't it is broken, although you might not notice it.
如果没有,它会被打破,尽管你可能没有注意到它。
For that you may move your logic from main method to constructor of class and call constructor as follows: 为此,您可以将逻辑从main方法移动到类的构造函数并调用构造函数,如下所示:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
You can also write logic in some other method then constructor. 您还可以在其他方法中使用构造函数编写逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.