Java 动态添加JCombobox和JTextField

Java 动态添加JCombobox和JTextField,java,swing,actionlistener,jtextfield,jcombobox,Java,Swing,Actionlistener,Jtextfield,Jcombobox,当组合框中选择了一个项目时,我想向面板添加一个JComboBox和一个JTextField 我有这个面板的代码 aantallenGebruikt.add(new JTextField("", 5)); onderdelenGebruikt.add(new JComboBox(onderdelenBox())); onderdelenGebruikt.get(0).addActionListener(MyFrame.this); panelAfronden = new JPanel(); pa

当组合框中选择了一个项目时,我想向面板添加一个
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");
    }
我知道如何将组合框和文本字段添加到面板中,但目前它甚至没有将
测试打印到控制台上

您的问题:

我知道如何将combobox和textfield添加到面板中,但目前它甚至没有将测试打印到控制台

答复:

JcomboBox
的引用存储在某个位置,然后在
ActionListener
中检查源代码

这样做:

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

    comboBox.addActionListener(MyFrame.this);
您的
ActionListener
将如下所示

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

我刚刚这么做了,但是如何在我将动态添加的
onderderLengeBRUIKT
中侦听其他组合框的事件呢?我已经更新了我的帖子。请仔细看看,您可以定义一个单一的
ActionListener
,它一次用于多个
JComboBox
。只要在
ActionListener
中检查source的实例,如果我这样做
onderdelnr=newjcombobox(onderdelenBox());添加(onderdelnr);JTextField onderdealantal=新的JTextField(“,5”);aantallenGebruikt.add(OnDedereAntal);面板2.添加(OnDerDelnR);面板2.添加(OnDedereAntal)它应该可以工作?很抱歉它不能工作。不能在不同面板中两次添加同一构件。您已经为每个
JComboBox
以及
JTextArea
创建了单独的实例
到上面的代码,在
onderdelnr=newjcombobox(onderdelenBox())之后它就像一个符咒