我只想为ComboBox设置自定义列表模型。评论的代码也没有奏效。我完全不知道为什么!
我在JDK 1.8下的Intellij Community Edition工作
import jssc.SerialPortList;
import javax.swing.*;
import java.awt.*;
public class sampleForm extends JFrame {
private JComboBox comboBox1;
private JPanel panel1;
/*public sampleForm() {
super("title");
String[] portNames = SerialPortList.getPortNames();
setLayout(new FlowLayout());
comboBox1 = new JComboBox(portNames);
add(comboBox1);
}*/
public static void main(String[] args) {
JFrame frame = new JFrame("sampleForm");
frame.setContentPane(new sampleForm().panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void createUIComponents() {
// TODO: place custom component creation code here
String[] portNames = SerialPortList.getPortNames();
comboBox1 = new JComboBox(port);
}
}
答案 0 :(得分:0)
您的类已经是JFrame
,但您在main
方法中创建了另一个JFrame实例。因此,您在sampleForm
构造函数中添加的任何内容都不会直观影响,因为sampleForm
实例不是您显示的框架。您正在显示新的JFrame
实例。所以相反,做
public sampleForm() {
super("title");
String[] portNames = SerialPortList.getPortNames();
comboBox1 = new JComboBox(portNames);
panel1 = new JPanel(); // default FlowLayout
panel.add(comboBox1);
setContentPane(panel1);
}
public static void main(String[] args) {
sampleForm frame = new sampleForm("sampleForm");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
另请参阅Initial Threads。 Swing应用程序应该在Event Dispatch Thread上运行。