Reading Selected Radio Button on button click - java

I am trying to get the value of the selected radio button on button click. This is what I managed to do but I am getting null as a result.
//Buttons Declared
JRadioButton choice1 = new JRadioButton("Choice 1");
JRadioButton choice2 = new JRadioButton("Choice 2");
JRadioButton choice3 = new JRadioButton("Choice 3");
JRadioButton choice4 = new JRadioButton("Choice 4");
choice1.setSelected(true);
//Buttons Grouped
ButtonGroup group = new ButtonGroup();
group.add(choice1);
group.add(choice2);
group.add(choice3);
group.add(choice4);
JPanel radioPanel = new JPanel();
radioPanel.add(choice1);
radioPanel.add(choice2);
radioPanel.add(choice3);
radioPanel.add(choice4);
JButton button = new JButton("Check Choice");
button.addActionListener(new ClickListener(group));
frame.add(button, BorderLayout.SOUTH);
//Calling Action Listener to read Radio Button Selected
static class ClickListener implements ActionListener{
ButtonGroup group = new ButtonGroup();
public ClickListener(ButtonGroup group){
super();
this.group = group;
}
public void actionPerformed(ActionEvent e){
System.out.println(group.getSelection().getActionCommand());
}
}

You never set the action commands of your JRadioButtons. So, when you ask for it, you're getting null.
Solution:
Where you first make the buttons:
choice1.setActionCommand("1");
choice2.setActionCommand("2");
choice3.setActionCommand("3");
choice4.setActionCommand("4");
then in your actionPerformed method:
String cmd = group.getSelection().getActionCommand();
if(cmd.equalsIgnoreCase("1")) {
// Button 1 Action
} else if(cmd.equalsIgnoreCase("2")) {
// Button 2 Action
} else if(cmd.equalsIgnoreCase("3")) {
// Button 3 Action
} else if(cmd.equalsIgnoreCase("4")) {
// Button 4 Action
}
This allows you to use the action commands to differentiate between the buttons. It isn't the cleanest way, but it should work.
Hope this helped!

Your ActionListener can query your four JRadioButton instances and check which one is selected with JRadioButton's isSelected() method.
If you want an event to occur when you click a JRadioButton and wish to know what JRadioButton was clicked, you could add an ActionListener to your JRadioButtons and then check if the ActionEvent originated from a specific JRadioButton with something like, e.getSource() == radioButton1.

You should make all the JRadioButton's static including the ButtonGroup.
Then you need to change the button listener:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(java.awt.event.ActionEvent arg0) {
System.out.println(group.getSelection().getActionCommand());
}
});
And to fix the NullPointerException, use this for all your radiobuttons:
choice1.setActionCommand("Choice 1");

This should work for you:
public class Example extends JFrame implements ActionListener {
private ButtonGroup group = null;
private JRadioButton choice1 = new JRadioButton("Choice 1");
private JRadioButton choice2 = new JRadioButton("Choice 2");
private JRadioButton choice3 = new JRadioButton("Choice 3");
private JRadioButton choice4 = new JRadioButton("Choice 4");
public Example() {
choice1.addActionListener(this);
choice2.addActionListener(this);
choice3.addActionListener(this);
choice4.addActionListener(this);
group = new ButtonGroup();
group.add(choice1);
group.add(choice2);
group.add(choice3);
group.add(choice4);
JPanel radioPanel = new JPanel(new FlowLayout());
radioPanel.add(choice1);
radioPanel.add(choice2);
radioPanel.add(choice3);
radioPanel.add(choice4);
add(radioPanel);
setSize(400, 400);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton radio = null;
if (e.getSource() instanceof JRadioButton) {
radio = (JRadioButton) (e.getSource());
}
if (radio.equals(choice1)) {
System.out.println(choice1.getText());
}
}

Related

Creating GUI components dynamically in java

So, we can create for example a button dynamically:
panel.add(new JButton("Button"));
validate();
But the question is, how do we make calls to those elements later? For example, how do I add an event listener to this button created above, like, 100 lines of code later?
Create a variable for your JButton:
JButton jButton = new JButton("Button");
panel.add(jButton);
validate();
/*
*
*
100 lines of code
*
*/
// add an event listener
jButton.addActionListener((ActionEvent) -> {
// do something
});
I've always created my buttons before adding to the panel like so
private JPanel buttonPanel() { //button panel method containting
JPanel panel = new JPanel();
JButton addButton = new JButton("Add");
addButton.setToolTipText("Add Customer Data");
JButton editButton = new JButton("Edit");
editButton.setToolTipText("Edit selected Customer");
JButton deleteButton = new JButton ("Delete");
deleteButton.setToolTipText("Delete selected Customer");
addButton.addActionListener((ActionEvent) -> {
doAddButton();
});
editButton.addActionListener((ActionEvent) -> {
doEditButton();
});
deleteButton.addActionListener((ActionEvent) -> {
doDeleteButton();
});
panel.add(addButton);
panel.add(editButton);
panel.add(deleteButton);
return panel;
}
Allows you do something like this later on.
private void doAddButton() { //provides action for add button
CustomerForm customerForm = new CustomerForm(this, "Add Customer", true);
customerForm.setLocationRelativeTo(this);
customerForm.setVisible(true);
}
In order to bind event listeners or other functionality into the button, you'd need to store a reference to it in a variable. So, instead of
panel.add(new JButton("Button"));
You could initialize the button with
JButton myButton = new JButton("Button");
panel.add(myButton);
and then later in your code
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something
}
});

Select a JRadionButton from group and print out an int value

I have five RadionButtons with values from 1 to 5. According to my selection i want to print out the value.
JRadioButton rOneStar = new JRadioButton();
rOneStar.setActionCommand(Integer.toString(1));
JRadioButton rTwoStars = new JRadioButton();
rTwoStars.setActionCommand(Integer.toString(2));
JRadioButton rThreeStar s= new JRadioButton();
rThreeStars.setActionCommand(Integer.toString(3));
JRadioButton rFourStars = new JRadioButton();
rFourStars.setActionCommand(Integer.toString(4));
JRadioButton rFiveStars = new JRadioButton();
rFiveStars.setActionCommand(Integer.toString(5));
// group stars
ButtonGroup starGroup = new ButtonGroup();
starGroup.add(rOneStar);
starGroup.add(rTwoStars);
starGroup.add(rThreeStars);
starGroup.add(rFourStars);
starGroup.add(rFiveStars);
Now I have multiple ActionListeners that print out the value. But in my opinion it's way too much code.
rOneStar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.getActionCommand();
System.out.println(starGroup.getSelection().getActionCommand());
}
});
rTwoStars.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.getActionCommand();
System.out.println(starGroup.getSelection().getActionCommand());
}
});
... and so on
Can anyone give me a hint please how I can shorten my code?
Depends what you want to do further but with the code snippet given by you, you could refactor a bit by extracting two methods:
private JRadioButton createJRadioButton(int x){
final JRadioButton rXStar = new JRadioButton();
rXStar.setActionCommand(Integer.toString(x));
return rXStar;
}
private ActionListener createActionListener(){
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.getActionCommand();
System.out.println(starGroup.getSelection().getActionCommand());
}
};
}
This would reduce your code and make it a bit nicer, like so:
JRadioButton rOneStar = createJRadioButton(1);
JRadioButton rTwoStars = createJRadioButton(2);
JRadioButton rThreeStar = createJRadioButton(3);
JRadioButton rFourStars = createJRadioButton(4);
JRadioButton rFiveStars = createJRadioButton(5);
// group stars
ButtonGroup starGroup = new ButtonGroup();
starGroup.add(rOneStar);
starGroup.add(rTwoStars);
starGroup.add(rThreeStars);
starGroup.add(rFourStars);
starGroup.add(rFiveStars);
rOneStar.addActionListener(createActionListener());
rTwoStars.addActionListener(createActionListener());
rThreeStars.addActionListener(createActionListener());
rFourStars.addActionListener(createActionListener());
rFiveStars.addActionListener(createActionListener());

Change font style of JTextField when JCheckbox is ticked and JButton is clicked

I don't get the result I want in this code, which is when I click on the checkbox then the JTextField's text should be bold, but It doesn't happen. Help me please.
public class GUI extends JFrame{
//CheckBoxs
private JCheckBox box1;
private JCheckBox box2;
//Buttons
private JButton button1;
private JButton button2;
//Text
private JTextField fnam;
private JTextField snam;
public GUI(){
//basic
super("Program");
setLayout(new FlowLayout());
//add
box1 = new JCheckBox("Button 1 Activate");
box2 = new JCheckBox("Button 2 Activate");
add(box1);
add(box2);
button1 = new JButton("Select First Name");
button2 = new JButton("Select Second Name");
add(button1);
add(button2);
fnam = new JTextField("Mena Farid",10);
snam = new JTextField("Malak Mamdoh",12);
fnam.setEditable(false);
snam.setEditable(false);
fnam.setFont(new Font("Serif",Font.PLAIN,10));
snam.setFont(new Font("Serif",Font.PLAIN,12));
add(fnam);
add(snam);
//ActionListener and Events
Handler Handle = new Handler();
Handler2 Handle2 = new Handler2();
box1.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(box1.isSelected())
button1.addItemListener(Handle);
}
}
);
box2.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(box2.isSelected())
button2.addItemListener(Handle2);
}
}
);
}
private class Handler implements ItemListener{
public void itemStateChanged(ItemEvent f){
Font font = null;
font = new Font("Serif",Font.BOLD,10);
fnam.setFont(font);
}
}
private class Handler2 implements ItemListener{
public void itemStateChanged(ItemEvent f){
Font font2 = null;
font2 = new Font("Serif",Font.BOLD,12);
snam.setFont(font2);
}
}
}
The problem is The JTextField format is supposed to be turned into bold after I tick the checkbox and click the button but It doesn't happen.
#LuxxMiner ow.. Thanks you fixed my problem . I have been using ItemListener for button instead of ActionListener all the time and that was the problem.

Action Listener on a radio button

I would like to set editable option of a text box based on the selection of a radio button? How to code the action listener on the radio button?
This is the solution that I would use in this case.
//The text field
JTextField textField = new JTextField();
//The buttons
JRadioButton rdbtnAllowEdit = new JRadioButton();
JRadioButton rdbtnDisallowEdit = new JRadioButton();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup editableGroup = new ButtonGroup();
editableGroup.add(rdbtnAllowEdit);
editableGroup.add(rdbtnDisallowEdit);
//add allow listener
rdbtnAllowEdit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setEditable(true);
}
});
//add disallow listener
rdbtnDisallowEdit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setEditable(false);
}
});
My Java is a little rusty, but this should be what you're looking for.
Here is your listener:
private RadioListener implements ActionListener{
private JTextField textField;
public RadioListener(JTextField textField){
this.textField = textField;
}
public void actionPerformed(ActionEvent e){
JRadioButton button = (JRadioButton) e.getSource();
// Set enabled based on button text (you can use whatever text you prefer)
if (button.getText().equals("Enable")){
textField.setEditable(true);
}else{
textField.setEditable(false);
}
}
}
And here is the code that sets it up.
JRadioButton enableButton = new JRadioButton("Enable");
JRadioButton disableButton = new JRadioButton("Disable");
JTextField field = new JTextField();
RadioListener listener = new RadioListener(field);
enableButton.addActionListener(listener);
disableButton.addActionListener(listener);
Another answer for this question. Modify a little code from zalpha314 's answer.
You could know which radio button is selected by the text of this button, and you could also know it by Action Command. In the oracle's radio button demo code http://docs.oracle.com/javase/tutorial/uiswing/examples/components/RadioButtonDemoProject/src/components/RadioButtonDemo.java , I learnt how to use action command.
First, define two action command
final static String ON = "on"
final static String OFF = "off"
Then add action command to buttons
JRadioButton enableButton = new JRadioButton("Enable");
enableButton.setActionCommand(ON);
JRadioButton disableButton = new JRadioButton("Disable");
disableButton.setActionCommand(OFF);
So in actionPerformed, you could get the action command.
public void actionPerformed(ActionEvent e){
String ac = e.getActionCommand();
if (ac.equals(ON)){
textField.setEditable(true);
}else{
textField.setEditable(false);
}
}
Action command maybe better when the button.getText() is a very long string.
Try this:
JRadioButton myRadioButton = new JRadioButton("");
myRadioButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// Do something here...
}
});
Try this:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NewStudent {
public static void main(String[] args){
NewStudent st=new NewStudent();
}
public NewStudent(){
JFrame frame=new JFrame("STUDENT REGISTRATION FORM");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setVisible(true);
JPanel p1=new JPanel();
p1.setLayout(null);
p1.setBackground(Color.CYAN);
frame.add(p1);
ButtonGroup buttonGroup=new ButtonGroup();
JRadioButton male=new JRadioButton("MALE");
male.setBounds(100,170,100,20);
buttonGroup.add(male);
p1.add(male);
JRadioButton female=new JRadioButton("FEMALE");
female.setBounds(250,170,100,20);
buttonGroup.add(female);
p1.add(female);
JLabel sex =new JLabel("SEX:");
sex.setBounds(10,200,100,20);
p1.add(sex);
final JTextField gender= new JTextField();
gender.setBounds(100,200,300,20);
p1.add(gender);
male.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ie){
gender.setText("MALE");
}
});
female.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ie){
gender.setText("FEMALE");
}
});
}

isSelected not returning true or false for JRadioButton

I have a program where I calculate for either 1 of 2 variables depending on the radio button selected. For some reason, isSelected() is not returning true or false. I will post my code below:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class FutureValueFrame extends JFrame {
public FutureValueFrame() {
setTitle("Sample App");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JFrame f = new FutureValueFrame();
//GUI and BUTTONS
JRadioButton monthlyRadioButton = new JRadioButton("Monthly Payment");
JRadioButton loanAmountButton = new JRadioButton("Loan Amount");
ButtonGroup selection = new ButtonGroup();
selection.add(monthlyRadioButton);
selection.add(loanAmountButton);
JFormattedTextField loanAmountField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField interestRateField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField yearField = new JFormattedTextField(new DecimalFormat("####.##"));
JFormattedTextField monthlyPaymentField = new JFormattedTextField(new DecimalFormat("####.##"));
JPanel menuPanel = new JPanel();
menuPanel.setLayout(new GridLayout(1,2));
//ACTION LISTENER FOR RADIO BUTTONS
monthlyRadioButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton, loanAmountField, monthlyPaymentField));
loanAmountButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton, loanAmountField, monthlyPaymentField));
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1,2));
topPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
topPanel.add(monthlyRadioButton);
topPanel.add(loanAmountButton);
JPanel botPanel = new JPanel();
botPanel.setLayout(new GridLayout(4,2));
botPanel.add(new JLabel("Loan Amount:"));
botPanel.add(loanAmountField);
botPanel.add(new JLabel("Yearly Interest Rate:"));
botPanel.add(interestRateField);
botPanel.add(new JLabel("Number of Years:"));
botPanel.add(yearField);
botPanel.add(new JLabel("Monthly Payment:"));
botPanel.add(monthlyPaymentField);
JPanel container = new JPanel();
container.setLayout(new GridLayout(3,1));
container.add(topPanel);
container.add(botPanel);
container.add(menuPanel);
f.add(container);
JButton calculateButton = new JButton("Calculate");
if (monthlyRadioButton.isSelected()){
calculateButton.addActionListener(new CalculateMonthlyListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
}
if (loanAmountButton.isSelected()){
calculateButton.addActionListener(new CalculateLoanListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
}
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(new ExitListener());
menuPanel.add(calculateButton);
menuPanel.add(exitButton);
f.setVisible(true);
f.setLocationRelativeTo(null);
}
class CalculateMonthlyListener implements ActionListener {
private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;
private JFormattedTextField interestRateField;
private JFormattedTextField yearField;
private float result;
public CalculateMonthlyListener (JFormattedTextField loanAmountField, JFormattedTextField interestRateField, JFormattedTextField yearField, JFormattedTextField monthlyPaymentField)
{
this.interestRateField = interestRateField;
this.yearField = yearField;
this.loanAmountField = loanAmountField;
this.monthlyPaymentField = monthlyPaymentField;
}
public void actionPerformed(ActionEvent event){
monthlyPaymentField.setValue(new Double(12.22));
System.out.println("You selected monthly");
}
}
class CalculateLoanListener implements ActionListener {
private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;
private JFormattedTextField interestRateField;
private JFormattedTextField yearField;
private float result;
public CalculateLoanListener (JFormattedTextField loanAmountField, JFormattedTextField interestRateField, JFormattedTextField yearField, JFormattedTextField monthlyPaymentField)
{
this.interestRateField = interestRateField;
this.yearField = yearField;
this.loanAmountField = loanAmountField;
this.monthlyPaymentField = monthlyPaymentField;
}
public void actionPerformed(ActionEvent event){
loanAmountField.setValue(new Double(12.22));
System.out.println("You selected loan");
}
}
class ExitListener implements ActionListener {
public void actionPerformed(ActionEvent event){
//f.dispose();
System.exit(0);
//System.out.println("You clicked exit");
}
}
class SelectionListener implements ActionListener {
private JRadioButton monthlyRadioButton;
private JRadioButton loanAmountButton;
private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;
public SelectionListener (JRadioButton monthlyRadioButton, JRadioButton loanAmountButton, JFormattedTextField loanAmountField, JFormattedTextField monthlyPaymentField)
{
this.monthlyRadioButton = monthlyRadioButton;
this.loanAmountButton = loanAmountButton;
this.loanAmountField = loanAmountField;
this.monthlyPaymentField = monthlyPaymentField;
}
public void actionPerformed(ActionEvent event){
if(event.getSource() == monthlyRadioButton){
loanAmountField.setEditable(false);
monthlyPaymentField.setEditable(true);
}
else {
monthlyPaymentField.setEditable(false);
loanAmountField.setEditable(true);
}
}
}
}
I believe the problem occurs at this snippet:
if (monthlyRadioButton.isSelected()){
calculateButton.addActionListener(new CalculateMonthlyListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
}
if (loanAmountButton.isSelected()){
calculateButton.addActionListener(new CalculateLoanListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
}
isSelected is not returning true. I've tried creating an int i and setting it to 1. I checked for i==1 in each condition and they executed correctly.
Any insights?
You should put selection checking code in a single action listener attached to your button, not decide which action listener to attach to the button based on the selection.
Replace the code you think is the source of your problem with this:
calculateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (selection.getSelection().equals(monthlyRadioButton.getModel())) {
monthlyPaymentField.setValue(new Double(12.22));
System.out.println("You selected monthly");
} else {
loanAmountField.setValue(new Double(12.22));
System.out.println("You selected loan");
}
}
});
In order for this to compile you'll have to make the variables accessed in the above action listener final. Or replace both CalculateMonthlyListener and CalculateLoanListener with a single class which does the same as shown above.
Note that I did not use JRadioButton.isSelected() directly but instead used your ButtonGroup.getSelection(). You could also check the radio buttons themselves.
isSelected is fired from JRadioButton after ActionListener is done
then
use ItemListener (always fired twice) with to check for SELECTED / DESELECTED
and
put JRadioButtons to the ButtonGroup, ActionCommand returns String value
calculateButton has no assigned listener due to two things:
At the beginning both radio buttons are not selected. Set one as selected then the proper calculateButton listener will be assigned in proper if statements.
In actionPerformed method of SelectionListener you don't set a new calculateButton listener. Change that.

Categories

Resources