Swing – RadioButton ItemListner Java

In this example, We will show swing RadioButton ItemListner Java program. This example program has been tested and shared with the output in the same post.

Sample Program

package com.dineshkrish;
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
* 
* @author Dinesh Krishnan
*
*/
public class RadioButtonExample extends JFrame {
private JPanel panel;
private ButtonGroup gender;
private JRadioButton male;
private JRadioButton female;
private JLabel label;
public RadioButtonExample(String title) {
// setting window properties
super.setTitle(title);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setSize(300, 100);
super.setVisible(true);
// setting the layout
super.setLayout(new BorderLayout());
init();
}
private void init() {
panel = new JPanel();
gender = new ButtonGroup();
male = new JRadioButton("Male");
female = new JRadioButton("Female");
// adding radio buttons to button group
gender.add(male);
gender.add(female);
// adding ItemListner
male.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
showSelectedValue();
}
});
// adding ItemListner
female.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
showSelectedValue();
}
});
panel.add(male);
panel.add(female);
label = new JLabel();
add(panel, BorderLayout.NORTH);
add(label, BorderLayout.SOUTH);
}
private void showSelectedValue() {
if (male.isSelected()) {
label.setText("You are : " + male.getActionCommand());
} else if (female.isSelected()) {
label.setText("You are : " + female.getActionCommand());
}
}
public static void main(String[] args) {
new RadioButtonExample("Radio Button Example");
}
}

Output

Swing RadioButton ItemListner Java Example

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *