This simple example shows you how to create a JRadioButton
component. To create an instance of JRadioButton
we can simply call its constructor and pass a string as the radio button text.
We can also call the constructor with a boolean
value after the text to indicate whether the radio button is selected or not.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class RadioButtonCreate extends JFrame {
public RadioButtonCreate() {
initializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new RadioButtonCreate().setVisible(true));
}
private void initializeUI() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 2));
JPanel leftPanel = new JPanel();
JLabel label = new JLabel("Employees: ");
leftPanel.add(label);
JPanel rightPanel = new JPanel(new GridLayout(4, 1));
// Create a JRadioButton by calling the JRadioButton constructors and
// passing a string for radio button text. We can also pass a boolean
// value to select or unselect the radio button.
JRadioButton radio1 = new JRadioButton("1 - 10");
JRadioButton radio2 = new JRadioButton("11 - 50", true);
JRadioButton radio3 = new JRadioButton("51 - 100");
JRadioButton radio4 = new JRadioButton("101 - 1000", false);
rightPanel.add(radio1);
rightPanel.add(radio2);
rightPanel.add(radio3);
rightPanel.add(radio4);
getContentPane().add(leftPanel);
getContentPane().add(rightPanel);
pack();
}
}
Latest posts by Wayan (see all)
- How do I add an object to the beginning of Stream? - February 7, 2025
- 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