how to select a radiobutton in buttongroup in Java - 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

Related

how to setChecked radio button in programmatically (radio button created in dynamically ) android

I try that
radioButton.setChecked(true);
but its only work 4th radio button. I try to create radio button dynamically. I create radio buttion within for loop, then store the radio button value. Then restore the radio button value (that means, I have 4 options that time I choose 2nd option and saved it then restore it(setChecked 2nd option) ) but its only setChecked 4th option.
Create radioButton.
for (int k = 0; k < choiceElementList.size(); k++) {
if (choiceElementList.get(k).dataFormatId == 1) {
radioButton = new RadioButton(getContext());
radioButton.setText(choiceElementList.get(k).getDataFormatValue());
radioButton.setLayoutParams(params1);
radioButton.setPadding(0, 5, 0, 5);
Log.e("setid", String.valueOf(choiceElementList.get(k).getId())) ;
radioGroup.addView(radioButton);
}
}
Try to restore that
if(choiceElementList.get(k).getId() == Cons.Id){
radioButton.setChecked(true);
}
First set Ids to your RadioButtons
for (int k = 0; k < choiceElementList.size(); k++) {
if (choiceElementList.get(k).dataFormatId == 1) {
RadioButton radioButton = new RadioButton(getContext());
// Set ID to Radio Button
radioButton.setId(k);
radioButton.setText(choiceElementList.get(k).getDataFormatValue());
radioButton.setLayoutParams(params1);
radioButton.setPadding(0, 5, 0, 5);
Log.e("setid", String.valueOf(choiceElementList.get(k).getId())) ;
radioGroup.addView(radioButton);
}
}
now just use your RadioGroup to check desire RadioButton with its ID
if(choiceElementList.get(k).getId() == Cons.Id){
radioGroup.check(k); // K will be your ID Set for your desire RadioButton
}
Happy Coding...
according to this code segments, your radioButton variable only refer last created element (radiobutton). That's why it only marks fourth one. You need to get correct reference for radio button what u want.
This is because you're adding all your RadioButton in a RadioGroup. When a RadioButton is checked in a RadioGroup, the othe RadioButton will be unchecked. You can see the RadioGroup documentation say it clearly:
This class is used to create a multiple-exclusion scope for a set of radio buttons. Checking one radio button that belongs to a radio group unchecks any previously checked radio button within the same group.
Intially, all of the radio buttons are unchecked. While it is not possible to uncheck a particular radio button, the radio group can be cleared to remove the checked state.
The selection is identified by the unique id of the radio button as defined in the XML layout file.

Clear Selection of RadioButtons

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.

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.

get the name of the selected radio button from button group

I want to return selected radio button name from button group in java :
ButtonGroup bg = new ButtonGroup();
bg.add(radiobutton1);
bg.add(radiobutton2);
bg.add(radiobutton3);
I think you can loop through the radio buttons, for each button if isSelected() is true then call button.getText() to get the name.
for (AbstractButton button : bg.getElements())
if (button.isSelected())
return button.getText();
Why do you want the button name? It isn't of much use. You can, however, get the all of the button references using bg.getElements(), and you can get the text of each of those references with button.getText(), both of which are of much more use than the name you gave the button. If you REALLY want the name, you can create the buttons and then call radiobutton1.setName("radiobutton1") and then use getName() on the reference.

Java Swing JTextField setInputVerifier keep focus on TextField

I have a public class JdbDateTextField extends JTextField and in the constructor I add this.setInputVerifier(new ValidDateOrEmptyVerifier());.
I use class ValidDateOrEmptyVerifier extends InputVerifier to verify the format of the input.
If the input is in the wrong format and the user looses the focus of the JdbDateTextField, I return false in the ValidDateOrEmptyVerifier and the focus is gained again to the JdbDateTextField again.
This works if the user switches from the JdbDateTextField to another textField or presses a Button. If pressing a button and the format of the input in the is wrong then no action for the button is performed and the focus is still at the JdbDateTextField.
This is exactly what I want. The user can not leave the JdbDateTextField until he enters a valid string.
The problem is that the JdbDateTextField is in a JPanel which is in a JTabbedPane so I have a GUI with several tabs.
If I have the JdbDateTextField selected, enter a invalid input and then directly click on another tab it still switches the tab. So I was able to provide a wrong input.
My Question is:
Is there a way to perform an Input Verification which does not allow to execute any other event before it is true
The best solution I can think of is to assign the JTabbedPane a custom selection model which refuses to allow changing tabs unless the current InputVerifier succeeds:
int index = tabbedPane.getSelectedIndex();
tabbedPane.setModel(new DefaultSingleSelectionModel() {
#Override
public void setSelectedIndex(int index) {
Component focusOwner =
FocusManager.getCurrentManager().getFocusOwner();
if (focusOwner instanceof JComponent) {
JComponent c = (JComponent) focusOwner;
InputVerifier verifier = c.getInputVerifier();
if (verifier != null && !verifier.shouldYieldFocus(c)) {
return;
}
}
super.setSelectedIndex(index);
}
});
tabbedPane.setSelectedIndex(index);
I hope that I can do this as an answer:
The solution above works for the JTabbedPane
But I can still select other GUI elements.
My Application is build like this:
For every Person ID I show other Birthdate values in the JTabbedPane
and I can still switch to another Person ID if the ValidDateOrEmptyVerifier returns false.
So is there a way to disallow all events in the Main Frame until the ValidDateOrEmptyVerifier returns true.
So Basically what I want is that the user can only exit the "Birthdate" JdbDateTextField if he enters a valid Date or the field is empty.

Categories