Here is an example code that creates a JFrame filled with various Swing components, each with its own ActionListener:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingComponentsExample extends JFrame {
public SwingComponentsExample() {
setTitle("Swing Components Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new FlowLayout());
// Create JButton
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(SwingComponentsExample.this, "Button clicked");
}
});
add(button);
// Create JCheckBox
JCheckBox checkBox = new JCheckBox("Check me");
checkBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean selected = checkBox.isSelected();
JOptionPane.showMessageDialog(SwingComponentsExample.this, "Checkbox selected: " + selected);
}
});
add(checkBox);
// Create JTextField
JTextField textField = new JTextField(10);
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
JOptionPane.showMessageDialog(SwingComponentsExample.this, "Text entered: " + text);
}
});
add(textField);
// Create JRadioButton
JRadioButton radioButton1 = new JRadioButton("Option 1");
radioButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(SwingComponentsExample.this, "Option 1 selected");
}
});
add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Option 2");
radioButton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(SwingComponentsExample.this, "Option 2 selected");
}
});
add(radioButton2);
// Create JComboBox
String[] options = {"Option 1", "Option 2", "Option 3"};
JComboBox<String> comboBox = new JComboBox<>(options);
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedOption = (String) comboBox.getSelectedItem();
JOptionPane.showMessageDialog(SwingComponentsExample.this, "Selected option: " + selectedOption);
}
});
add(comboBox);
}
public static void main(String[] args) {
SwingComponentsExample example = new SwingComponentsExample();
example.setVisible(true);
}
}
This code creates a JFrame window and adds various Swing components, including JButton, JCheckBox, JTextField, JRadioButton, and JComboBox. Each component has its own ActionListener that will perform a specific action when triggered.