How do I create a ButtonGroup for radio buttons?

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);
    }
}

How do I create JRadioButton and define some action?

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);
    }
}

How do I create a JRadioButton component?

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();
    }
}

How do I place swing component using absolute coordinates?

In this example you can see how we do an absolute positioning to a swing component in the content panel. In this example we use a JPanel as the container, and we didn’t set a layout manager into it.

To position the component on the container we use the setBounds() method of the component. This method takes the x and y coordinate position and also the width and height of the component.

package org.kodejava.swing;

import javax.swing.*;

public class AbsolutePositionDemo extends JFrame {
    public AbsolutePositionDemo() {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new AbsolutePositionDemo().setVisible(true));
    }

    private void initializeUI() {
        setSize(400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(null);

        JTextField textField = new JTextField(20);
        textField.setBounds(50, 50, 100, 20);

        JButton button = new JButton("Button");
        button.setBounds(200, 100, 100, 20);

        JCheckBox checkBox = new JCheckBox("Check Me!");
        checkBox.setBounds(300, 250, 100, 20);

        panel.add(textField);
        panel.add(button);
        panel.add(checkBox);

        setContentPane(panel);
    }
}

How do I arrange the swing component using GridLayout?

This example use the GridLayout to create a four by four grid layout. One each of the grid we place a JTextField component to read user inputs.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;

public class GridLayoutDemo extends JFrame {
    public GridLayoutDemo() {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new GridLayoutDemo().setVisible(true));
    }

    private void initializeUI() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Create a four by four GridLayout with 5 pixel horizontal and vertical
        // gap between each row or column.
        GridLayout grid = new GridLayout(4, 4, 5, 5);
        //grid.setColumns(4);
        //grid.setRows(4);
        //grid.setHgap(5);
        //grid.setVgap(5);

        setLayout(grid);

        JTextField[][] textFields = new JTextField[4][4];
        for (int i = 0; i < textFields.length; i++) {
            for (int j = 0; j < textFields[i].length; j++) {
                textFields[i][j] = new JTextField(String.valueOf((i + 1) * (j + 1)));
                // Put the text at the center of the JTextField component
                textFields[i][j].setHorizontalAlignment(SwingConstants.CENTER);

                getContentPane().add(textFields[i][j]);
            }
        }
    }
}