关于带有 actionlistener 的 JComboBox 的问题

Issue about JComboBox with actionlistner

对于下面的示例,我正在编写一个包含数据 1,3,5,7,9 的 JComboBox,并期望在按下 OK 后它会变为 2,4,6,8,10。然而它就是行不通.....任何建议将不胜感激,谢谢。

public class Test extends JFrame{

Test (){
    final ArrayList<Integer> value = new ArrayList<>();
    value.add(1);                                                           
    value.add(3);                                                          
    value.add(5);                   
    value.add(7);
    value.add(9);
    final JComboBox pulldown = new JComboBox(value.toArray());
    add(pulldown);

    JButton ok = new JButton("OK");
    add(ok);

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
         int data [] = {2,4,6,8,10};                                       
         value.clear();
         for (int i=0; i < data.length; i++)
         {
         value.add(data[i]);  
         System.out.println(data[i]);
         }
        }
    });


}

public static void main(String[] args) {
    JFrame frame = new Test();
    frame.setLayout(new FlowLayout());
    frame.setSize(320, 240);
    frame.setVisible(true);
    frame.setResizable(true);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

}

您正在使用 ArrayList 数据来设置 JComboBox 的 model(此处可能是 DefaultComboBoxModel),但稍后更改 ArrayList 的数据不应该也可能不会更改设置模型后的模型(尽管对于其他集合可能存在发生这种情况的风险)。

最好继续使用 DefaultComboBoxModel 开始。

DefaultComboBoxModel<Integer>  model = new DefaultComboBoxModel<>();
model.addElement(1);                                                           
model.addElement(3);                                                          
model.addElement(5);                   
model.addElement(7);
model.addElement(9);

final JComboBox pulldown = new JComboBox(model);

然后您可以稍后更改模型的数据,并确保更改将反映在 JComboBox 的数据显示中。

要从 JComboBox 中删除所有旧值,您需要调用方法 myComboBox.removeAllItems() 并向其中添加新项目,您需要调用 myComboBox.addItem(myobject)。更改这部分代码,

ok.addActionListener(new ActionListener() {


            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                pulldown.removeAllItems();//removing all previous items
                int data[] = { 2, 4, 6, 8, 10 };
                value.clear();
                for (int i = 0; i < data.length; i++) {
                     pulldown.addItem(data[i]);//adding new items
                }
            }
        });