How to avoid firing actionlistener event of JComboBox when an item is get added into it dynamically in java?

后端 未结 9 2284
广开言路
广开言路 2020-12-04 00:23

I need your suggestions and guidence on following task.

I have a frame which has two JComboBoxes supposed they are named combo1 and combo2, a JTable and other compon

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 00:50

    To avoid that addItem method fire events is better to use an DefaultComboBoxModel in the JComboBox to add data. Also, if you invoke a model.addElement(), an event is fired, so, you can add all the elements to the model and later use JComboBox.setModel(model). In this way, if you add elements to the model, events are not fired because you have not link the JComboBox with the model. Then, I show you an example.

    private void rellenarArrendatarioComboBox(ArrayList arrendatarios) {
        DefaultComboBoxModel model = new DefaultComboBoxModel();
        model.addElement(new Arrendatario(" -- Seleccione un arrendatario --"));
        for (Arrendatario arrendatario : arrendatarios) {
            model.addElement(arrendatario);
        }
        ArrendatarioComboBox.setModel(model);
    }
    

    First, we create the model, add all elements to the model (events are not fired because you have not link the JComboBox with the model), we link the model with the JComboBox using ArrendatarioComboBox.setModel(model). After linking, events are fired.

提交回复
热议问题