简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM