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

后端 未结 9 2256
广开言路
广开言路 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:47

    try this:

           indicatorComboBox = new JComboBox() {
    
            /**
             * Do not fire if set by program.
             */
            protected void fireActionEvent() {
                // if the mouse made the selection -> the comboBox has focus
                if(this.hasFocus())
                    super.fireActionEvent();
            }
        };
    
    0 讨论(0)
  • 2020-12-04 00:49

    You could remove the action listener before you add the new elements, and add it back once you're done . Swing is single threaded so there is no need to worry about other threads needing to fire the listener.

    Your listener could probably also check if something is selected and take appropriate action if not. Better than getting a NPE.

    0 讨论(0)
  • 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<Arrendatario> 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.

    0 讨论(0)
提交回复
热议问题