Below we create a JRadioButton
and pass an action handle to the component so that we know when the component is clicked.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class RadioButtonCreateAction extends JFrame {
public RadioButtonCreateAction() {
initializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new RadioButtonCreateAction().setVisible(true));
}
private void initializeUI() {
setSize(300, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JRadioButton button = (JRadioButton) e.getSource();
System.out.println("actionPerformed " + button.getText());
}
};
// Create a radio button and pass an AbstractAction as its constructor.
// The action will be call everytime the radio button is clicked or
// pressed. But when it selected programmatically the action will not
// be called.
JRadioButton button = new JRadioButton(action);
button.setText("Click Me!");
button.setSelected(true);
getContentPane().add(button);
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023