Sauri Vega
Sauri Vega

Reputation: 11

The listener of a checkbox doesn't work with a button

(I'm not native english speaker, but I'll try my best)

Hi, I have a problem with a jcheckbox, I created this using this code

try (ResultSet rs = st.executeQuery("SELECT * FROM cuentas ")) {
                while (rs.next()) {
                    cmb[i] = new javax.swing.JCheckBox();
                    cmb[i].setLabel(rs.getObject("cuentascol").toString());
                    jPanel15.add(cmb[i]);
                    cmb[i].setBounds(20, 20 + (i * 20), 160 + (i * 20), 23 + (i * 20));
                    cmb[i].addItemListener(new ItemListener() {
                        @Override
                        public void itemStateChanged(ItemEvent evt) {
                            JCheckBox cb = (JCheckBox)evt.getItem();
                        }
                    });
                    i = i + 1;
                }
            }

and I found how to add them a listener, but the listener only works when the button is selected or not by clicking them, and I need to check if this is selected but when i press a button, the button take a number from this

int comboNum=1;
                    for(int pp=0;pp<total_checkbox;pp++){

                        comboNum=comboNum+1;
                    }

Is in this button where i need to check if the jcheckbox is selected

Upvotes: 1

Views: 71

Answers (1)

Jean-Fran&#231;ois Savard
Jean-Fran&#231;ois Savard

Reputation: 21004

Because you are creating an ItemListener and override the itemStateChanged method.

The doc specify

Invoked when an item has been selected or deselected by the user.

Which explain why it is not called when you simply click.

You might want to use a ChangeListener instead and override the method stateChanged.

Invoked when the target of the listener has changed its state.

Check this sample for how to detect different event like press, selected etc.

Upvotes: 1

Related Questions