Which radio button is selected in a button group - java

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;
}
}

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

How to prevent empty context menu from showing in GXT

I have a TreePanel which shows different kind of objects hierarchically. Region, City, Location...
I want to be able to show different context menu items in different levels. For example: miR for Region, miC for City, miL for Location...
I used this snipped to achieve that dynamic structure:
contextMenu.addListener(Events.BeforeShow, new Listener<MenuEvent>() {
#Override
public void handleEvent(MenuEvent be) {
//First make all menu items invisible
List<Component> menuItems = contextMenu.getItems();
for (Component c : menuItems) {
c.setVisible(false);
}
//And make apprepriate menu items visible
TopologyTreeElement s = tree.getSelectionModel().getSelectedItem();
if (s instanceof TopologyTreeElement.Region) {
miR.setVisible(true);
}
if (s instanceof TopologyTreeElement.City) {
miC.setVisible(true);
}
}
});
But, in any level if all of the items are invisible, it shows an empty box. I want it not to show the menu totally. I tried adding this code snippet to the method, but it gave no help.
//Do not show menu if no menu item is invisible
boolean isMenuShouldBeVisible = miC.isVisible() || miR.isVisible();
if (!isMenuShouldBeVisible) {
be.preventDefault();
be.stopEvent();
}
Anyone can suggest a different approach?
Since you are listening to the BeforeShow event, you are allowed to cancel the event and stop the actual Show event from happening. Check to see if all items are invisible, and if so, call be.setCancelled(true).
Any event that starts in Before can be used to cancel the later event - this is why these before- events exist at all.

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.

setSelected a specific jradiobutton in a buttongroup based on action command

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.

Simplest way of creating java next/previous buttons

I know that when creating buttons, like next and previous, that the code can be somewhat long to get those buttons to function.
My professor gave us this example to create the next button:
private void jbtnNext_Click() {
JOptionPane.showMessageDialog(null, "Next" ,"Button Pressed",
JOptionPane.INFORMATION_MESSAGE);
try {
if (rset.next()) {
fillTextFields(false);
}else{
//Display result in a dialog box
JOptionPane.showMessageDialog(null, "Not found");
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
Though, I do not really understand how that short and simple if statement is what makes the next button function. I see that the fillTextFields(false) uses a boolean value and that you need to initialize that boolean value in the beginning of the code I believe. I had put private fillTextFields boolean = false; but this does not seem to be right...
I'm just hoping someone could explain it better. Thanks :)
Well, fillTextFields(true); is a function call and when you pass in a true/false flag it does some things (you have to see the code inside the function in order to find out exactly what it does).
The field declaration private fillTextFields boolean = false; is invalid, you're supposed to provide the type before the name, e.g.: private boolean fillTextFields = false;. Aside from the invalid syntax that flag really doesn't do anything, especially if you're not using it anywhere.
I don't understand what else you expect to see in the jbtnNext_Click() method... when you declare your button and it gets clicked on the UI, then this method gets invoked. It doesn't make the button work, the button works even when you have nothing in the jbtnNext_Click() method. For example:
private void jbtnNext_Click() {
// The button will still work, but it simply won't do anything
}
Getting a button to function depends on what you view as a functioning button. What is supposed to happen when you click next/previous?
Update:
I thought that I needed the boolean
declaration to make the
"fillTextFields(false)" work.
Was the fillTextFields method given to you somewhere? If it was, then you don't need to declare anything, much less a variable. If it's already provided, then you just call the method, that's all. If it's not provided then you need to declare it:
private void fillTextFields(bool shouldFill)
{
if(shouldFill)
{
// fill the text fields
}
// possibly have an else statement if you need to do something else here
}
Otherwise what you see in that function is all you need to do in order to go to the next record in the database.
I think that the code provided is a bit short to provide a good explanation, posting the code for fillTextFields would be of more help.
What I can guess that the program is doing is that it is retrieving some data from a database. The next button allows the program to iterate through the items that have been returned.
Once that the next button is pressed, a message box is shown to let you "know" that the button has indeed been pressed.
rset.next returns true of there is another element in the list (retrieved from the database), or false if there isn't.
If it returns true, you are calling the fillTextFields methods, which I guess displays the data on screen (even though without the code I can just speculate). If there isn't anything left, a message box displaying "Not Found" is shown.
With regards to your question about
private fillTextFields boolean = false;
fillTextFields is a method, and you cannot assign values to methods. Also, in Java, when declaring both methods and variables, the type is written before the name, such as
private int number;
public float myMethod() { }
The next button won't do anything unless you register an action with the button. What I mean is, wherever your next button is defined looks something like this:
private JButton nextButton = new JButton("Next");
This creates a button that has the label, 'Next'. There might be some additional code for positioning the button. In order for that button to do anything when it is clicked, it needs to have an Action set on it, or it has to have an ActionListener added to it. Many times, the class that is creating the button implements ActionListener and has a method to respond to the click, something like:
nextButton.addActionListener(this);
...
...
...
public void actionPerformed(ActionEvent e) {
// some method implementation
}
The actionPerformed method is called when the button is clicked, AS LONG AS you've registered the action listener on the button. Is anything like this present in the code from your professor?

Categories

Resources