Swing Controls

Swing provides a set of controls (also known as components) to create interactive user interfaces. These controls are part of the javax.swing package and can be easily added to containers like JPanel and JFrame.


Common Swing Controls

ControlDescription
JButtonButton that triggers an action when clicked.
JLabelDisplays a short string or an image.
JTextFieldA single-line text input field.
JTextAreaA multi-line text input field.
JCheckBoxA checkbox for binary choices (checked/unchecked).
JRadioButtonA radio button for selecting one option from a group.
JComboBoxA dropdown menu for selecting from a list of items.
JListA list that allows selecting one or more items.

Example: Using JButton and JLabel

JFrame frame = new JFrame("Swing Controls");
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Hello, World!");

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        label.setText("Button Clicked!");
    }
});

frame.add(button, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

Example: JCheckBox

JCheckBox checkBox = new JCheckBox("Agree to terms");
checkBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            System.out.println("Checked");
        } else {
            System.out.println("Unchecked");
        }
    }
});

Example: JComboBox

String[] items = { "Java", "Python", "C++", "JavaScript" };
JComboBox<String> comboBox = new JComboBox<>(items);
comboBox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String selectedItem = (String) comboBox.getSelectedItem();
        System.out.println("Selected: " + selectedItem);
    }
});