2014-06-05 23 views
0

我只想爲ComboBox設置自定義列表模型。評論的代碼也沒有奏效。我完全不知道爲什麼!在intellij中自定義組件創建失敗

我在的IntelliJ社區版工作JDK 1.8

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

你的類已經是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上運行。