setSelected a specific jradiobutton in a buttongroup based on action command - java

i want to setSelected a speicfic jradiobutton in a buttongroup based on the actionCommand(/name of the specific jradiobutton).
it could be done usind .setSelected(true)
for example,
JRadioButton rabbitButton = new JRadioButton("rabbit");
rabbitButton .setActionCommand("rabbit");
JRadioButton pigButton = new JRadioButton("pig");
pigButton .setActionCommand("pig");
ButtonGroup group = new ButtonGroup();
group.add(rabbitButton);
group.add(pigButton);
now.. without ,
{ rabbitButton.setSelected(true);} NOR {group.setSelected(rabbitButton.getModel,true)}
is there a way to setSelected(true) rabbitButton based on the action command()?

yourButtonGroup.clearSelection();
yourRadioButton.setSelected(true);

I created a small method that allow me to set any radio group button. Very convenient if you don't want to use if for any radio button.
public void setButtonGroup(String rdValue, Enumeration elements ){
while (elements.hasMoreElements()){
AbstractButton button = (AbstractButton)elements.nextElement();
if(button.getActionCommand().equals(rdValue)){
button.setSelected(true);
}
}
}
then
setButtonGroup(yourValue, yourButtonGroup.getElements());

The ButtonGroup#getElements method gives you an enumeration of AbstractButton instances. The AbstractButton#getActionCommand allows you to retrieve the action command and the AbstractButton#getSelected allows you to alter the selection.
So there is a way, but you will have to loop over the enumeration yourself.

Related

How to Check(Marked as checked) buttons in a program(or a checkbox) from just one Button?

Here is my question.Lets say that somebody made a checkbox in java and he is using it in a GUI interface so that the user can select a variety of options.Then the programmer wants to create a button inside the checkbox so that when the user checks that button all the other options will be checked as well.And when he unchecks that button of course all the other buttons will be unchecked.How is that possible in java?
Example :
o1 = new JCheckBox("Option 1");
o2 = new JCheckBox("Option 2");
o3 = new JCheckBox("Option 3");
All = new JCheckBox("All");
.....
CheckBoxHandler listener = new CheckBoxHandler();
All.addItemListener(listener);
......
Lets assume that the following code is on a class that was created as it implements ItemListener
public class CheckBoxHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
if (e.getSource()==All)
if (e.getStateChange()==ItemEvent.SELECTED)
{
.... <------ (!!!)Here inside I am currently stack and I do not know how to
add the correct code in order to have all the other buttons checked.
}
}
}
Any help provided is really appreciated :)
Make use of the concept of array.
JCheckBox[] checkboxes = new JCheckBox[10];
When you need to apply some operation to all checkboxes, iterate over the array:
for( JCheckbox cb : checkboxes )
cb.doStuff();
You can call setSelected() on the JCheckbox (inherited from AbstractButton):
...
o1.setSelected(true); // or false
...
As #Juvanis mentions, instead of having three different references for o1, o2 and o3, you should use an array. Then, you can do something like
for( JCheckbox cb : checkboxes ) {
cb.setSelected(true);
}
to set all checkboxes in the array as checked.
CheckBoxes can have ActionListeners. Why not add an ActionListener to all the checkboxes that then checks if the one selected is checked or not and calls setSelected(true) or setSelected(false) on each one?
If you have a known small number of checkboxes (such as the 3 you talked about), you may just want to hard code it. However, if you need to make it modular or have a large number of check boxes, you can always store them in a data structure (as Juvanis said, an array would probably work nicely) and loop it

Referring to a Dynamically Created JButton

I have a JPanel on which I've dynamically added quite a few JButtons. All of this is working perfectly. Later on in my program execution, I need to refer back to these buttons and pull out the button text. I'm having trouble figuring out how to refer back to them.
When I created each button, I gave it a unique name. Let's say this is the code where I created the button:
public void createButton(Container parent, String btnName) {
JButton btn = new JButton("xyz");
btn.setName(btnName);
btn.addActionListner(new ActionListner() {
//code
}
parent.add(btn);
}
In another method, I'm trying to retrieve the label on the button since it may have changed at run time. Do I need to keep an array of these buttons as they are created? Or is there a way that I can refer back to them directly?
This is what I was working on, but it's stupid. Can anyone suggest a correct approach?
public String getBtnLabel(String btnName) {
JButton btn = (JButton) btnName;
return btn.getText();
}
If the answer is that I just need to create the array and then iterate over it, that's fine. Just looking for other options.
You need to use a Map<String, JButton> so when you create your dynamic buttons you give them some sort of unqiue name:
//somewhere at the top of your class
private final Map<String, JButton> myButtonMap = new HashMap<>();
public void createButton(Container parent, String btnName) {
JButton btn = new JButton("xyz");
btn.setName(btnName);
btn.addActionListner(new ActionListner() {
//code
}
parent.add(btn);
myButtonMap.put(btnName, btn);
}
And then simply get from the map
public String getBtnLabel(String btnName) {
return myButtonMap.get(btnName).getText();
}
This will obviously throw an NPE if the button isn't defined...
Also you will need to delete from your map when you're done with it otherwise you're asking for a memory leak...
I suggest you to use a Map< String, JButton >.
At creation time you put new button into it with buttons.put( name, btn )
In event handler you use JButton btn = buttons.get( name )
Yes you need to keep references to the buttons. An array would be an option, but since arrays are awkward to use, you should prefer a List.
If you have a a reference to the JPanel containing the buttons, you could get them from it. but that is likely to be rather bothersome.
I would recommend keeping a list of your buttons or a reference to them in a map, however you could do this:
for (Component i : parent.getComponents()) {
if (i.getName().equals(btnName)) {
JButton b = (JButton) i;
// do stuff..
}
}
Using the parent component and iterating over the added components.

Java swing - same handler for multiple controls

I was wondering whether there is any other way to handle and event coming from any of N controls, which would read the ActionCommand value and act based on that. So far I basically have a defitinion of ActionListener which I add to each of the controls individually. For instance, if I have 50 checkboxes, I would like to write a method like
void process(){
getCommandValueAndDoSth();
}
but rather than instantiate ActionListener for all the checkboxes, I would like just to control all the checkboxes.
You can have one listener for all of your components.
ActionListener al = new ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// either do it like this
process(e.getActionCommand());
// or like this to distinguish between the controls
if (e.getSource() == firstElement) processChangeInFirstElement();
else if (e.getSource() == secondElement) processChangeInSecondElement();
// etc
}
}
Component firstElement = new JCheckBox("asdf");
firstElement.addActionListener(al);
Component secondElement = new JTextField();
secondElement.addActionListener(al);
If you need to have multiple types of listeners (ChangeListener, MouseListener, ActionListener, KeyListener, ...), then you have one instance of each of those listener types and apply them to the corresponding components.
You can attach the same ActionListener to multiple components (e.g. to all your Checkboxes). The handler just needs to be able to derive all the required information from the ActionEvent (if required it can get to the component using event.getSource()).
In my case I just wanted to know if any control in the window had been changed and should allow the user to "apply" those changes. You can actually add them pretty easily with lambdas. Below are examples for JCheckBox, JComboBox<>, and JXDatePicker. Both JTextField/JTextArea are a little more complicated and require document listeners.
chckbx.addItemListener(e -> process()); //Check box itemListeners don't trigger when hovering
comboBox.addActionListener(e -> process()); //Triggered when selection changes
datePicker.addActionListener(e -> process()); //When date changes
addChangeListener(txtField, e -> process()); //Text field needs a documentListener
The code for the text field's document listener addChangeListener.

Java: Iterate JMenuItem from ArrayList with HashMaps

I have a JFrame with a menubar, in which i'd like some dynamic menus, as in, depending on the size of the ArrayList with HashLists. The problem here is that i then got a dynamic amount of JMenuItems, so i need a way to get as much variables as HashLists. In this case i made the name of the variable static, but obviously that's not working on the ActionListener, since all MenuItems will have the same ActionListener.
I'm wondering how to solve this, and how to get a menu with a dynamic amount of menuitems which all have unique actionlisteners.
private ArrayList<HashMap> menuLijst;
.
for (HashMap h : menuLijst) {
String vraag = (String) h.get("vraag");
JMenuItem qMenu = new JMenuItem(vraag);
informatie.add(qMenu);
qMenu.addActionListener(this);
}
Thanks in advance.
Depending on what you want to do in your ActionListener, you can either use this, as you do right now and in the actionPerformed you can then use ((JMenutItem)event.getSource()) to see which menu item has been clicked. Alternatively, you could register as many ActionListeners as there are menus, like this:
for (final HashMap h : menuLijst) {
final String vraag = (String) h.get("vraag");
final JMenuItem qMenu = new JMenuItem(vraag);
informatie.add(qMenu);
qMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// here event.getSource() is the same as qMenu
System.out.println("Menu "+qMenu+" with label "+vraag+" has been pressed");
System.out.println("HashMap is "+h);
}
});
}
But to me (and also seeing your previous questions), it seems that you are abusing the usage of HashMap instead of using appropriate new objects. I don't know what else is in your HashMap, let's say that you have 3 keys: "vraag", "answer", "grade", you could create the following class:
public class MyClass {
private String vraag;
private String answer;
private int grade;
// And getters and setters here.
}
And have a List<MyClass> instead of List<HashMap>.
I don't see why you want to use a HashMap for your Strings. If you save an ArrayList of Strings, and loop over them to add them all to the menu, you can add actionListeners to all of them, just as you are doing now.
In your ActionListener, check which button is clicked by looping through the ArrayList, and comparing to the name of the clicked button.

Which radio button is selected in a button group

What can I do to get which radiobutton is selected on a buttongroup without doing this:
if (jRadioButton1.isSelected()) {
//...
}
if (jRadioButton2.isSelected()) {
//...
}
if (jRadioButton3.isSelected()) {
//...
}
if (jRadioButton4.isSelected()) {
//...
}
You can get the ButtonModel for the selected button via the getSelection() method of ButtonGroup. I don't know how you can avoid conditionally branching on the selected button though, unless you have some sort of ancillary data structure mapping from ButtonModel to actions to perform, for instance. If you had that, then you could just fire the action based on the returned ButtonModel.
Darryl's Select Button Group has a getSelectedButton() method.
I know the question was posted long back. Anyway, we can use the setActioncommand function. while creating the radio button, setActionCommand could be invoked to set the action command value, which could be used to refer to the radio button that was selected.
jRadioButton1.setActionCommand("jRadioButton1");
jRadioButton2.setActionCommand("jRadioButton2")
.
.
String button_name = ((JToggleButton.ToggleButtonModel)button_group.getSelection()).getActionCommand();
ButtonGroup class does not provide a method to identify the currently selected button (inherited from AbstractButton) in the group if that is your intention. It only has clearSelection() method to clear the selected state of all buttons in the group (with exception for JButton and JMenuItem which don't have select/deselect button state).
One solution I can think of is to use a special variable or field (AbstractButton, JRadioButton or JRadioButtonMenuItem if it is in a menu item) to identify which one is currently selected by updating it inside each AbstractButton's action listener method (make sure to validate user clicks since it can be triggered more than once!). Use the variable (by typecasting it - for AbstractButton only) in other method(s).
Other than that, nope...you will need to do conditional branching.
For dealing with a button group bg, you can get the buttons by calling the button group's getElements() method, and using that as the parameter for the Collections.list() method, just save the result in an arraylist. From there it is relatively simple to retrieve the correct button.
ArrayList<AbstractButton> arl = Collections.list(bg.getElements());
for (AbstractButton ab : arl) {
JRadioButton jrb = (JRadioButton) ab;
if (jrb.isSelected()) {
return jrb;
}
}

Categories

Resources