Reputation: 827
I am writing a Java App that has multiple items available to test. However -- due to HW limitations, I can only test 4 devices in parallel. I was wondering -- in genera -- how can I get Java to limit the number of selected items to only four (no matter which ones are picked)? I am reading through the Java docs and I can't seem to find the answer to that.
I am fairly new to Java -- so please forgive my ignorance. I just need a clue as to where/how to start.
How do I limit the number of check boxes selected in Java?
Upvotes: 0
Views: 2164
Reputation: 3070
If you're using Swing, start with creating an array of JCheckBox[] and fill it with checkboxes. Create then ChangeListener and global variable with amount of checked checkboxes. Add this listener to all of checkboxes. In ChangeListener's stateChanged()
method increase or decrease your global variable by 1. If variable reach four, disable all of checkboxes with setEnabled(false) except those which are checked. When you'll decrease your variable from 4 to 3, set them to enabled.
This is good example about ChangeListener: http://www.java2s.com/Code/Java/Event/CheckBoxItemListener.htm
Upvotes: 5
Reputation: 47269
Keep track of all of your checkboxes. Add a call to the following check in the stateChanged() in the listener:
Incrementing / decrementing a global count on the number of checkboxes might seem more slightly more efficient, but the gain is negligible when dealing with UIs. I would say it's better to code defensively to avoid corner cases and bugs from trying to keep track of state information rather than just polling it.
For defensive programming, you want to also validate the input from the UI to check that the number of checked boxes is less than or equal to 4.
Upvotes: 1
Reputation: 3635
I would create a global variable that can hold the count of devices started.
When a check box is clicked, in it's event handler, add to the variable if it was checked and subtract if it was unchecked.
Of course you would check before you add that the value was less than 5 (0 - 4) before allowing another to be checked.
Upvotes: 3