2014-04-05 42 views
0

我想添加一個JComboBox和一個JTextField到一個面板時,在組合框中選擇一個項目。動態添加JCombobox和JTextField

我有這個面板的代碼。

aantallenGebruikt.add(new JTextField("", 5)); 
onderdelenGebruikt.add(new JComboBox(onderdelenBox())); 
onderdelenGebruikt.get(0).addActionListener(MyFrame.this); 

panelAfronden = new JPanel(); 
panelAfronden.setLayout(new FlowLayout()); 

panelAfronden.add(new JLabel("Selecteer onderdeelNr en Vul gebruikte aantallen in")); 



panelAfronden2 = new JPanel(); 
panelAfronden2.setLayout(new FlowLayout()); 

panelAfronden2.add(onderdelenGebruikt.get(0)); 
panelAfronden2.add(aantallenGebruikt.get(0)); 

JScrollPane sPane = new JScrollPane(panelAfronden2); 
sPane.setPreferredSize(new Dimension(220, 230)); 

panelAfronden.add(sPane); 

panelAfronden.add(new JLabel("Opmerkingen")); 
opmerkingenAfronden = new JTextArea(5, 20); 
panelAfronden.add(opmerkingenAfronden); 

rondAf = new JButton("Rond Werkzaamheid Af"); 
rondAf.addActionListener(MyFrame.this); 
panelAfronden.add(rondAf); 

annuleer = new JButton("Annuleer"); 
annuleer.addActionListener(MyFrame.this); 
panelAfronden.add(annuleer); 

我有這樣的ActionListener的

if(eventSource == onderdelenGebruikt){ 
     System.out.println("test"); 
    } 

我知道如何組合框和文本框添加到面板上,但目前,它甚至沒有打印出來的test到控制檯

回答

0

您的問題:

我知道如何將組合框和文本框添加到面板,但此刻它d甚至不會將測試打印到控制檯上。

答:

商店JcomboBox一些地方,然後檢查源ActionListener的參考。

做到這樣:

final JComboBox comboBox = new JComboBox(onderdelenBox()); 
    onderdelenGebruikt.add(comboBox); 

    comboBox.addActionListener(MyFrame.this); 

ActionListener會這個樣子。

if(eventSource == comboBox){ 
    System.out.println("test"); 
} 
+0

我剛剛那樣做了,但是如何在「onderdelenGebruikt」中監聽其他組合框的事件,我將動態添加? –

+0

我已更新我的帖子。請看看,您可以一次定義一個用於多個「JComboBox」的'ActionListener'。只需在'ActionListener'中檢查源代碼的實例。 – Braj

+0

所以如果我這樣做'onderdeelNr = new JComboBox(onderdelenBox()); \t \t \t onderdelenGebruikt.add(onderdeelNr); \t \t \t JTextField onderdeelAantal = new JTextField(「」,5); \t \t \t aantallenGebruikt.add(onderdeelAantal); \t \t \t \t \t \t panelAfronden2.add(onderdeelNr); \t \t \t panelAfronden2.add(onderdeelAantal);'它應該工作? –