Clear Selection of RadioButtons - java

My application: user wants the object to move left with a particular speed - he/she chooses one radiobutton from moveToLeft ButtonGroup. But he/she changes his/her mind and wants the object to move right - he/she chooses one radiobutton from moveToRight ButtonGroup.
My question is - how to clear buttongroup, that was chosen as first. I tried ClearSelection and setSelected(false), but it does not work. Here is my code:
JRadioButton vel1 = new JRadioButton("10 km/h");
JRadioButton vel2 = new JRadioButton("20 km/h");
JRadioButton vel3 = new JRadioButton("30 km/h");
JRadioButton vel4 = new JRadioButton("40 km/h");
ButtonGroup moveToRight = new ButtonGroup();
moveToRight.add(vel1);
moveToRight.add(vel2);
ButtonGroup moveToLeft = new ButtonGroup();
moveToLeft.add(vel3);
moveToLeft.add(vel4);
if(vel1.isSelected() || vel2.isSelected() )
{
moveToLeft.clearSelection();
//vel3.setSelected(false);
//vel4.setSelected(false);
}
if(vel3.isSelected() || vel4.isSelected() )
{
moveToRight.clearSelection();
//vel1.setSelected(false);
//vel2.setSelected(false);
}
The ButtonGroups are in two different panels.

What doesn't work? If the clearSelection(...) statement is executed, then it will work. If it doesn't work, then the statement is not executed.
The code you posted won't do anything. That code will be executed when the buttons are created and the frame isn't even visible yet, so obviously they will not yet be selected by the user.
...he/she chooses one radiobutton...
So then you need to add an ActionListener to the radio button to execute the relevant code.
Read the section from the Swing tutorial on How to Use Radio Buttons for more information and working examples.

Related

How to check condition that 'only one jRadiobutton should be selected'

I am working on details entry form on NetBeans with Java Swings. There are three certain jRadiobutton, of them only one must be selected.
Any methods that could give such power, please suggest. Or might I need to custom my own method to perform check?
You have to create a object of ButtonGroup and add radio buttons to that object.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setSelected(true);
JRadioButton catButton = new JRadioButton(catString);
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);

Java determining if which JRadioButton was selected

I know that it is possible in an event driven program in Java to find out what object caused an event (e.g. JRadioButton was selected, therefore a certain action will take place). My question is, if you have 2 JRadioButtons in a buttongroup, both with action listeners added to them, and you keep selecting from one to the other, is it possible to find out what JRadioButton was previously selected? In other words, if I selected another JRadioButton, is it possible to write code that determines which JRadioButton was previously selected before selecting the current JRadioButton?
public class Drinks extends JPanel implements ActionListener{
double drinksPrice = 2.10;
double noDrinks = 0;
static String selectedDrink;
JRadioButton btnPepsi = new JRadioButton("Pepsi"); //add a button to choose different drinks
JRadioButton btnMtDew = new JRadioButton("Mt Dew");
JRadioButton btnDietPepsi= new JRadioButton("Diet Pepsi");
JRadioButton btnCoffee = new JRadioButton("Coffee");
JRadioButton btnTea = new JRadioButton("Tea");
JRadioButton btnNone = new JRadioButton("None");
JLabel lblDrinksHeading = new JLabel("Choose a drink (each drink is $2.10):");
ButtonGroup drinksButtonGroup = new ButtonGroup();
private static final long serialVersionUID = 1L;
public Drinks(){
setLayout(new FlowLayout()); //Using GridLayout
btnPepsi.setActionCommand(btnPepsi.getText()); //set the ActionCommand to getText so I can retrieve the name for the receipt
btnMtDew.setActionCommand(btnMtDew.getText());
btnDietPepsi.setActionCommand(btnDietPepsi.getText());
btnCoffee.setActionCommand(btnCoffee.getText());
btnTea.setActionCommand(btnTea.getText());
btnNone.setActionCommand(btnNone.getText());
drinksButtonGroup.add(btnPepsi);
drinksButtonGroup.add(btnMtDew);
drinksButtonGroup.add(btnDietPepsi);
drinksButtonGroup.add(btnCoffee);
drinksButtonGroup.add(btnTea);
drinksButtonGroup.add(btnNone);
btnNone.setSelected(true); //set default to "none"
btnPepsi.addActionListener(this);
btnMtDew.addActionListener(this);
btnDietPepsi.addActionListener(this);
btnCoffee.addActionListener(this);
btnTea.addActionListener(this);
btnNone.addActionListener(this);
add(lblDrinksHeading);
add(btnPepsi);
add(btnDietPepsi);
add(btnMtDew);
add(btnCoffee);
add(btnTea);
add(btnNone);
repaint();
revalidate();
selectedDrink = drinksButtonGroup.getSelection().getActionCommand();
//add the drink price to totalPrice, it is adding it every time though, even if its none
/*if(drinksButtonGroup.getSelection() == btnNone){
MenuFrame.totalPrice += 0;
}
else{
MenuFrame.totalPrice += drinksPrice;
}
*/
// buttonGroup1.getSelection().getActionCommand()
//String selectedDrink = drinksButtonGroup.getSelection().toString();
//class
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == btnNone) {
MenuFrame.totalPrice += 0;
TaxAndGratuityFrame.subtotalTextField.setText("$" + MenuFrame.totalPrice);
TaxAndGratuityFrame.subtotalVariable = MenuFrame.totalPrice;
TaxAndGratuityFrame.taxVariable = TaxAndGratuityFrame.subtotalVariable * TaxAndGratuityFrame.TAX_RATE;
TaxAndGratuityFrame.taxTextField.setText("$" + TaxAndGratuityFrame.taxVariable);
Receipt.receiptTotal.setText("Total: $" + (MenuFrame.totalPrice));
Receipt.receiptsubtotal.setText("Subtotal: " + (TaxAndGratuityFrame.subtotalVariable));
}
else {
MenuFrame.totalPrice += drinksPrice;
TaxAndGratuityFrame.subtotalTextField.setText("$" + MenuFrame.totalPrice);
TaxAndGratuityFrame.subtotalVariable = MenuFrame.totalPrice;
TaxAndGratuityFrame.taxVariable = TaxAndGratuityFrame.subtotalVariable * TaxAndGratuityFrame.TAX_RATE;
TaxAndGratuityFrame.taxTextField.setText("$" + TaxAndGratuityFrame.taxVariable);
Receipt.receiptTotal.setText("Total: $" + (MenuFrame.totalPrice));
Receipt.receiptsubtotal.setText("Subtotal: " + (TaxAndGratuityFrame.subtotalVariable));
}
}
Edit: I'll be more specific. I am creating an "imaginary" restaurant program. In it, I list several drinks that have the same price (e.g. Pepsi: $2.10, Mountain Due: $2.10, etc). These listed drinks are JRadioButtons. Once a customer clicks one of these buttons to "order a drink", $2.10 will be added to a "total" variable. However, a problem occurs when a user wants to change there drink, because if they click a different JRadioButton, $2.10 will still be added to the "total" variable. I want to make it so that they can change there drink without adding $2.10 to the order every time.
I think the problem is at this line:
MenuFrame.totalPrice += drinksPrice;
Because "+=" increments a value by another value instead of simply adding two values.
So every time the user clicks on one of the radio buttons, it will continuously add 2.10 to your total value, whereas if you were you just say:
MenuFrame.totalPrice = MenuFrame.totalPrice + drinksPrice;
It will set your total price equal to the current total price plus the price of drinks, instead of adding 2.10 to the total value every time a button is pressed.
Perhaps I am misunderstanding the question, but I am thinking along the lines of creating a public variable, and then inside the action listeners updating the variable with the radio button that was just selected. When the selected event fires, you can look at the variable to see which radio button had last been selected, do what you want to about it, and then update it with the new radio button.

Java: JCheckBox won't stay checked with ItemListener

Ok, I'm new to listeners (still learning the language), and this is my first full-scale attempt to implement them (ie more than just a practice problem in a textbook).
So far, everything is working fine except one big bug: the checkboxes don't stay checked. The ItemListener I assign them runs perfectly (I have a JOptionPane set up to trigger to let me know if it's working or not), but the box itself doesn't stay checked.
I went even further and added conditional logic for if it's state is checked versus unchecked, and found that when I click the box BOTH states get triggered. So I get both JOptionPane popups, the one with the message for if the box is checked and the one for if the box isn't checked.
I'm including my code here. What am I doing wrong?
PS. You'll notice that the code has conditional logic to either add a radio button or a checkbox. When the program finally runs, this component is generated in multiple locations in both formats. The radio button works fine, it's the checkbox ones that I'm having the above issue with.
CODE THAT CREATES THE CHECKBOXES AND ASSIGNS THE LISTENERS:
public OtherField(int voteFor){
this.voteFor = voteFor;
otherPanel = new JPanel();
otherPanel.setLayout(new GridLayout(1, 3));
otherField = new JTextField(10);
otherField.setHorizontalAlignment(SwingConstants.CENTER);
JLabel otherLabel;
otherLabel = new JLabel("Other", SwingConstants.CENTER);
otherRadio = new JRadioButton("", false);
otherRadio.setHorizontalAlignment(SwingConstants.CENTER);
otherRadio.addActionListener(new OtherFieldRadioListener());
otherCheckBox = new JCheckBox("");
otherCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
otherCheckBox.addItemListener(new OtherFieldCheckBoxListener());
otherPanel.add(otherLabel);
otherPanel.add(otherField);
if(voteFor == 1){
otherPanel.add(otherRadio);
}else{
otherPanel.add(otherCheckBox);
}
}
LISTENER CODE (it's a private class in the same class as the code above):
private class OtherFieldCheckBoxListener implements ItemListener{
public void itemStateChanged(ItemEvent e){
String name = otherField.getText();
if(e.getStateChange() == ItemEvent.SELECTED){
JOptionPane.showMessageDialog(null, name);
}else{
JOptionPane.showMessageDialog(null, "Not Selected");
}
}
}
First thing I would try is to set the checkbox either to true or false when you initialize it, i.e
otherCheckBox.setSelected(false)
If this does not work I would check whether OtherField gets called from somewhere else everytime the checkbox is selected and thus the components are redrawn/ the selection is reset (use the debugger and set a breakpoint at the beginning of OtherFields)

Apply common code to group of jbuttons

Is it possible to apply a common code to multiple jbuttons in a frame on click of any jbutton.
Its like when I click, say jbutton80, then:
from jbutton1 to jbutton75
{
// common code that applies to all jbutton in loop
}
I am making quiz app in java and have around 70-80 buttons in jframe. Each button corresponds to a question. Questions are divided in sections.
So I want:
//if user selects(or clicks on jbutton) section a setvisible(true) from jbutton1 to jbutton20 and setvisible(false) from jbutton21 to jbutton 80.
Sorry, if this question has been asked before. I tried to search any relevant post but couldn't find one.
Did you try making an action listener
ActionListener l = new ActionListener() { /* code here */ };
And then adding the same one to all of the JButtons?
for (JButton b : buttons) {
b.addActionListener(l);
}

how to select a radiobutton in buttongroup in Java

I created several radio buttons in a button group but I cannot understand how to set necessary radio button in a code. My program reads the personal information in a file and shows it in the form (one person at a time). The personal information includes a marital status apart from name and other data, so I use radio buttons for the marital status.
This is my code (I used class Person with public enum MaritalStatus {SINGLE, MARRIED, WIDOW};):
buttonGroup = new ButtonGroup();
for (Person.MaritalStatus c : Person.MaritalStatus.values()) {
JRadioButton radioButton = new JRadioButton(c.name());
buttonGroup.add(radioButton);
if (c == mStatus) {
radioButton.setSelected(true);
}
radioButtonPanel.add(radioButton);
}
So, I have a group of radio buttons:
SINGLE, MARRIED, WIDOW
If user changes the person, the program must update the info about the marital status of the next person in a file. In other words, I don't know how to choose necessary radio button. The method of button group setSelected(buttonModel, bool) requires the buttonModel/radioButton name, but I don't have it in the code

Categories