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

How do I determine if the menu of JComboBox is displayed?

This example show how to create an implementation of PopupMenuListener for listening to when the JComboBox menu is visible, invisible or cancelled.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;
import java.awt.*;

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

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

    private void initialize() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        Integer[] years = new Integer[]{
                2016, 2017, 2018, 2019, 2020,
                2021, 2022, 2023, 2024, 2025
        };

        JComboBox<Integer> comboBox = new JComboBox<>(years);
        comboBox.setEditable(true);

        // Adds a PopupMenu listener which will listen to notification
        // messages from the popup portion of the combo box.
        comboBox.addPopupMenuListener(new PopupMenuListener() {
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                // This method is called before the popup menu becomes visible.
                System.out.println("PopupMenuWillBecomeVisible");
            }

            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                // This method is called before the popup menu becomes invisible
                System.out.println("PopupMenuWillBecomeInvisible");
            }

            public void popupMenuCanceled(PopupMenuEvent e) {
                // This method is called when the popup menu is canceled
                System.out.println("PopupMenuCanceled");
            }
        });

        getContentPane().add(comboBox);
    }
}