Get all selected checkboxes on button click [duplicate] - java

I have a dialog in Java that presents ~ 15 checkboxes to the user. Is there a way to get the names of all the checked checkboxes at once? Currently, I'm looking one by one if they are selected, which isn't that fancy of a solution.
I'm looking for something similar to Getting all selected checkboxes in an array but then in Java

When you are adding your Checkboxes to your dialog also keep a reference in a Collection of some sort. Then when you want to see which are checked you can just Iterate over the collection and check the state of each of them. You can get the name by calling getText on it.

List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
for( Component comp : panel.getComponents() ) {
if( comp instanceof JCheckBox) checkboxes.add( (JCheckBox)comp );
}
This assumes all of the JCheckBox instances are a direct child of the container panel. If not then you'd need to recursively visit all the containers of panel using the same logic. Now, while you can do this it's typically better to save these references as you created them into a list. Then you can easily iterate over all of the checkboxes without having to do this code above. If you have embedded components it's better to ask the embedded component to perform whatever operation you want over the checkboxes it owns (as opposed to pulling them out of the component through a getter so you can mess them in some way).

Related

What is a good practice to handle a lot of checkboxes in JavaFX

I need to build a View which has a 4 layer nested Multi-Accordion with a lot of checkboxes inside them. All together there might be around 30-40 Checkboxes all through the Accordions.
The next step will be, that i have some sort of logic behind all this. Depending on the selection combination of the checkboxes I will change a text label accordingly.
My thought process was: I put up all these checkboxes and give them a numeric fx:id representing there position in the nested accordion graph. Something like "1_1" or "2_4_1".
After that, I build one ChangeListener calling a Method on Selection of a Checkbox. I can look up the Id of the checked box, look it up in my data (to see which Text belongs to it and if any rules interfer with other boxes) and handle the logic accordingly while putting the id and its text in a Map or List to keep it for later and to keep track of the checked boxes.
Now I came to know, that getting the fx:id isnt something JavaFX wants me to do. I cant deliver a custom id in custom property inside the FXML either (couldnt find anything regarding this).
I am now pretty much at the end of my knowledge (I did just start with JavaFX and have some basic Java knowledge) and it seems to me, that I tackle this topic from the wrong side.
My question is now: What would be a best practice to handle dozens of checkboxes and trigger logic in the code according to the box that was checked without writing a ChangeListener for every single Check Box leaving me with some (imo) ugly code all the way.
EDIT: I forgot to mention: I did achieve some sort of functional solution by writing a custom CheckboxChangeListener with a reference to the Element the addListener method was called on and using "getId()" on this reference. I came to know though, that this method references the css:id of the fxml element and not its fx:id and I am not quite sure if this is a proper way to go
You should look into databinding with javafx. For example:
CheckBox cb1 = new CheckBox("1");
CheckBox cb2 = new CheckBox("2");
BooleanProperty isCb1Selected = cb1.selectedProperty();
BooleanProperty isCb2Selected = cb2.selectedProperty();
Textfield foo = new TextField().visibleProperty().bind(isCb1Selected.and(isCb2Selected));
This would hide the textfield foo if atleast one of the checkboxes isn't selected.
You can find other examples here and here an oracle tutorial

Creating a checkbox java list

i am trying to generate a checkbox list feeded by some records from a database just like the image (JAVA Swing), initially i tried with several chexkboxes but it didn't work, now i am trying with a multiple selection list but it didn't work as well and none of the answered questions here looks like to solve the specific needs i have.
Specifications:
Multiple selection list.
Every node of the list must have a checkbox object.
When checked every node must stay highlighted.
It must have an scrollbar if the content is bigger to the initially setted dimentions.
It must have an scrollbar if the content is bigger to the initially set dimensions.
Put the JList inside a JScrollPane.
When checked every node must stay highlighted.
This is going to confuse the user. The check marks are sufficient.
Every node of the list must have a check box object.
You'll have to extend a JList and a ListCellRenderer to gain this functionality. The ListSelectionListener that I have is over 100 lines of code.
You might find an already existing check box JList on the web. I have one in a book.

SWT ComboBoxCellEditor editable

I have a TableViewer where the values in one column should typically come from a dynamic list.
I'm currently using org.eclipse.jface.viewers.ComboBoxCellEditor , which is actually a Select-List: it stores the index of the selected value. If I change the underlying list (calling setItems(String[]), it's clumsy to keep the previous selected value... (specially if it's not included in the list anymore!) What I'd wish is actually a cell editor that stores, not the index from the list, but the string (perhaps letting the user edit it freely, perhaps not), where the list is just used as a suggestion at input time - like a "combobox" was supposed to work in the good old days... Is this possible?
I would suggest you to have your CellEditor to mimic the behavior that you are looking for. Extend ComboBoxViewerCellEditor and override doGetValue() method. Add modify listener on Combo control and also filter (which filters list items based on input text) to comboviewer.
You should look at :
org.eclipse.wst.xml.ui.internal.properties.StringComboBoxCellEditor This class comes from WTP project; It's an extended ComboBoxCellEditor that selects and returns Strings.
codemirror.eclipse.ui.xquery.viewers.StringComboBoxCellEditor It's the copy/paste of WTP StringComboBoxCellEditor; it adds the capability to add the item in the combo when it is not found.

Wicket : how to set checked value in CheckBoxMultipleChoice

I am using wicket's CheckBoxMultipleChoice to let the user set a list of options. so far it works fine. but then i want to add a "check all" check box that checks all the options in the CheckBoxMultipleChoice and I am having problems with that.
here is my initial code
ArrayList<String> chosen;
List<String> choices = Arrays.asList(new String[]{"Train", "Bus", "Car"});
CheckBoxMultipleChoice myCheck = new CheckBoxMultipleChoice("transport", new Model(chosen), choices));
myCheck.setOutputMarkupId(true);
form.add(myCheck);
on submit i print out the values of chosen and its "Bus", "Car" etc. as expected.
now i am adding a checkbox to check all the choices using ajax:
Boolean checkOrNot;
final CheckBox checkAll = new CheckBox("checkAll", new Model(checkOrNot));
form.add(checkAll);
checkAll.add(new AjaxFormComponentUpdatingBehavior("onchange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
// here i am not able to set the checkboxes
// i tried doing this
chosen.clear();
chosen.add(new String("Car"));
chosen.add(new String("Train"));
myCheck.modelChanged();
// i have also tried recreating the multiple choice
myCheck = new CheckBoxMultipleChoice<T>("transport", new Model(chosen), choices);
myCheck.setOutputMarkupId(true);
target.addComponent(myCgecj);
target.addComponent(form);
}
});
I am running out of ideas and wondering if anyone has any solutions? thanks in advance for any help.
I didn't (and can't) try that right now, so this is to be taken with a grain of salt, but couldn't you use a CheckGroup for that?
From the JavaDoc:
Component used to connect instances of Check components into a group. Instances of Check have to be in the component hierarchy somewhere below the group component. The model of the CheckGroup component has to be an instance of java.util.Collection. The model collection of the group is filled with model objects of all selected Check components.
So a
new Checkgroup("group", choices)
should work for you. No need to reimplement that functionality.
P.S.: I'll check that as soon as I've got the chance to do so...
You could use javascript to mark the checkboxes.
An example, using jQuery:
mycheck.setOutputMarkupId(true);
checkAll.add(new SimpleAttributeModifier("onclick",
"$('#" + mycheck.getMarkupId() + " input:checkbox').attr('checked', $(this).is(':checked'))");
Well, another way to go is to use
checkBoxMultipleChoice.setDefaultModelObject(listOfAllElements); // Select all.
checkBoxMultipleChoice.setDefaultModelObject(Lists.newArrayList()); // Deselect all.
I know that you fount already an answer but in my case I had exactly the same issue, but the option to use the CheckGroup was not feasible because my list is built dynamically and at the beginning it can even be empty.
The situation for me was:
I was obliged to use the CheckBoxMultipleChoice because it allows me to have empty lists thus reflecting in the GUI. CheckGroups will always print one check box without label, even if the options for the component are empty.
Using AjaxFormComponentUpdatingBehavior would throw an exception saying it was only possible to use it in other components.
Using OnChangeAjaxBehavior would work with the selector CheckBox (select/deselect) but if used with the CheckBoxMultipleChoice then the event will fire but the actual values of the component will not be reflected in the model within the event.
Thanks god I found This Forum in Nabble.
Basically here Pedro Santos propose to use the AjaxFormChoiceComponentUpdatingBehavior instead. I followed the advice and finally I was able to get the values in the model.
Sometimes I think Wicket is Wicked :P

Show/Hide JMenuItems in a JPopupMenu based on a JTree's selection

I have a JTree which displays a JPopupMenu when I right click nodes in the JTree. What is the best way to hide/show or enable/disable certain JMenuItems in my JPopupMenu based on the node selected in the JTree?
The first solution that came to mind was to add a TreeSelectionListener to the JTree for the 'value changed' event. In the event handling code I would use the TreeSelectionEvent's getNewLeadSelectionPath() method to get the path of the most recent selection, and use the resulting TreePath object's getLastPathComponent() to get the selected node. From here I would have a series of IF statements that access my JPopupMenu object and perform the modifications necessary to hide/show specific JMenuItems.
However, something feels off about this, and so I decided I would ask SO if there was a better approach.
The way that I chose to tackle this within my own app was to use the "userObject" property of the DefaultMutableTreeNode class which allows you to just store any data you want along with your node. I have a variety of types of things that extend from an abstract base class which defines a "createPopupMenu()" method. Then, in the selection listener (just as you described in your question) I get the user object and ask it to create a popup menu appropriate for the selected object and display that.
Getting the selected tree node is straight forward and should work as you described it. To modify the popup menu I would recommend using Actions. This way you wouldn’t have to modify your live menu and could also add e.g. a JToolBar that contains the same actions that react the same way the items in your menu do.

Categories

Resources