gpt4 book ai didi

java - Swing JComboBox 奇怪的行为

转载 作者:行者123 更新时间:2023-12-02 08:03:05 25 4
gpt4 key购买 nike

我观察到以下行为(在 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);
}
}

显示 HELLO,但如果我取消注释实例化 JComboBox 的行,它将不会显示任何内容。什么可能导致这种情况?您能够重现该错误吗?

最佳答案

我评论中的解决方案:

Move m.setVisible(true); at the end.

来自 Jens Schauder 的另一条评论:

Your code should also run in the EDT. Anything else is asking for trouble

也许他想告诉这样的事情:

涉及 Swing 组件的所有内容,包括构造 must run in the EDT 。如果没有,它就损坏了,尽管您可能没有注意到。

为此,您可以将逻辑从主方法移动到类的构造函数并调用构造函数,如下所示:

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}

您还可以在构造函数之外的其他方法中编写逻辑。

关于java - Swing JComboBox 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8602587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com