动态添加 JCombobox 和 JTextField



当组合框中选择了项目时,我想向面板添加JComboBoxJTextField

我有面板的这个代码。

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);

我在行动侦听器中有这个

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

我知道如何将组合框和文本字段添加到面板,但目前它甚至没有将test打印到控制台

您的问题:

我知道如何将组合框和文本字段添加到面板,但目前它甚至没有将测试打印到控制台。

答:

JcomboBox的引用存储在某个地方,然后在ActionListener中检查源。

以这种方式执行:

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

您的ActionListener将如下所示。

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

最新更新