This example shows you how to create a ButtonGroup
for grouping our radio buttons components into a single group. In this example you can also see that we add an action listener to the radio buttons.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonGroupDemo extends JFrame {
public ButtonGroupDemo() {
initializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new ButtonGroupDemo().setVisible(true));
}
private void initializeUI() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
// Creating an action listener for our radio button.
ActionListener action = e -> {
JRadioButton button = (JRadioButton) e.getSource();
System.out.println("You select button: " + button.getText());
};
// Creates four radio buttons and set the action listener.
JRadioButton button1 = new JRadioButton("One");
button1.addActionListener(action);
JRadioButton button2 = new JRadioButton("Two");
button2.addActionListener(action);
JRadioButton button3 = new JRadioButton("Three");
button3.addActionListener(action);
JRadioButton button4 = new JRadioButton("Four");
button4.addActionListener(action);
// Create a ButtonGroup to group our radio buttons into one group. This
// will make sure that only one item or one radio is selected on the
// group.
ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
group.add(button3);
group.add(button4);
getContentPane().add(button1);
getContentPane().add(button2);
getContentPane().add(button3);
getContentPane().add(button4);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024