java - How to calculate total checkboxes selected ? If (totalselected)>10 disable rest -
so im trying check if total number of checkboxes selected == 10. if i'm wanting disable rest of checkboxes aren't selected! meaning user can select 10 checkboxes.
i thinking for loop
loops through array , checks if checkbox selected , adds 1 counter. if counter reaches 10 thought may easy disable rest of checkboxes not!
list<checkbox> chksongs = new arraylist<checkbox>(); string labels[] = {"songa", "songb", "songc", "songd", "songe", "songf", "songg", "songh", "songi", "songj", "songk", "songl", "songm", "songn", "songo", "songp", "songq", "songr", "songs", "songt"} (int = 0; < labels.length; i++) { checkbox checkbox = new checkbox(labels[i]); chksongs.add(checkbox); formpanel.add(checkbox); }
here wrote on fly, think want:
public class checkboxframe extends jframe { public checkboxframe() throws headlessexception { jpanel formpanel = new jpanel(new gridlayout(-1, 4)); list<checkbox> chksongs = new arraylist<>(); string labels[] = {"songa", "songb", "songc", "songd", "songe", "songf", "songg", "songh", "songi", "songj", "songk", "songl", "songm", "songn", "songo", "songp", "songq", "songr", "songs", "songt"}; (string label : labels) { checkbox checkbox = new checkbox(label); chksongs.add(checkbox); formpanel.add(checkbox); } checkboxlistener listener = new checkboxlistener(chksongs, 10); setcontentpane(formpanel); setdefaultcloseoperation(jframe.exit_on_close); pack(); } public class checkboxlistener implements itemlistener { private int boxeschecked; private final list<checkbox> checkboxes; private final int maxselections; public checkboxlistener(list<checkbox> checkboxes, int maxselections) { this.checkboxes = new arraylist<>(objects.requirenonnull(checkboxes)); this.maxselections = maxselections; this.boxeschecked = (int) this.checkboxes.stream().filter(cb -> cb.getstate()).count(); this.checkboxes.foreach(cb -> cb.additemlistener(this)); } @override public void itemstatechanged(itemevent ie) { if (ie.getstatechange() == itemevent.selected) { boxeschecked++; } else { boxeschecked--; } if (boxeschecked == maxselections) { checkboxes.stream().filter(cb -> !cb.getstate()).foreach(cb -> cb.setenabled(false)); } else if (boxeschecked == maxselections - 1) { checkboxes.stream().foreach(cb -> cb.setenabled(true)); } } } public static void main(string[] args) { eventqueue.invokelater(new runnable() { @override public void run() { new checkboxframe().setvisible(true); } }); } }
this still has flaws (you add listener checkbox, example), it's not bad.
Comments
Post a Comment