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

How do I arrange the swing component using FlowLayout?

In this example you can see how to arrange the swing components using the FlowLayout manager. This manager arranges the component in a directional flow based on the container component orientation such as ComponentOrientation.LEFT_TO_RIGHT and ComponentOrientation.RIGHT_TO_LEFT.

package org.kodejava.swing;

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

public class FlowLayoutExample extends JFrame {
    public FlowLayoutExample() {
        initialize();
    }

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

    private void initialize() {
        setSize(250, 150);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Create a new FlowLayout manager and set the component arrangement to
        // left justified. The other arrangement if FlowLayout.CENTER,
        // FlowLayout.RIGHT, FlowLayout.LEADING and FlowLayout.TRAILING.
        FlowLayout layoutManager = new FlowLayout(FlowLayout.RIGHT);

        // Set the horizontal and vertical gap between component laid in the
        // content pane to 10 pixels.
        layoutManager.setHgap(10);
        layoutManager.setVgap(10);
        setLayout(layoutManager);

        // Set the container's component orientation from the right to left. 
        // This make the first component placed on the right top part of the
        // container.
        getContentPane().setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

        // Adds some JTextFields to the frame panel.
        JTextField[][] textFields = new JTextField[3][3];
        for (int i = 0; i < textFields.length; i++) {
            for (int j = 0; j < textFields[i].length; j++) {
                textFields[i][j] = new JTextField(5);
                textFields[i][j].setText(String.valueOf(((i + 1) * (j + 1))));

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

How do I arrange the swing component using BoxLayout?

This example demonstrate how we can arrange component in row or column order using the BoxLayout layout manager. Instead of use the BoxLayout manager we can also use the Box component as our content pane to get the same effect as using the BoxLayout manager.

package org.kodejava.swing;

import javax.swing.*;

public class BoxLayoutDemo extends JFrame {
    public BoxLayoutDemo() {
        initialize();
    }

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

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

        // Set the layout of the Content Pane to BoxLayout using BoxLayout.X_AXIS
        // will arrange the component left to right. We can use the BoxLayout.Y_AXIS
        // to arrange the component top to bottom.
        setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));

        JLabel label = new JLabel("Username : ");
        JTextField textField = new JTextField();

        JLabel password = new JLabel("Password :");
        JPasswordField passwordField = new JPasswordField();

        getContentPane().add(label);
        getContentPane().add(textField);

        getContentPane().add(password);
        getContentPane().add(passwordField);
    }
}