How do I create JCheckBox component?

This example demonstrate a various way to create JCheckBox component. Here you can also see how the handle an event when the checkbox is clicked by user.

package org.kodejava.swing;

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

public class CheckBoxDemoCreate extends JFrame {
    public CheckBoxDemoCreate() throws HeadlessException {
        initialize();
    }

    private void initialize() {
        setSize(500, 500);
        setTitle("JCheckBox Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Creating checkbox with text label
        JCheckBox checkBoxA = new JCheckBox("Selection A");

        // Creating checkbox with text label a set the state into checked
        JCheckBox checkBoxB = new JCheckBox("Selection B", true);

        // Creating checkbox with text label and a default unselected image icon
        ImageIcon icon = new ImageIcon(
                Objects.requireNonNull(
                        this.getClass().getResource("/images/lightbulb_off.png")));
        JCheckBox checkBoxC = new JCheckBox("Selection C", icon);
        // Add action listener to listen for click and change the image icon
        // respectively
        checkBoxC.addActionListener(e -> {
            JCheckBox checkBox = (JCheckBox) e.getSource();
            if (checkBox.isSelected()) {
                checkBox.setIcon(new ImageIcon(
                        Objects.requireNonNull(
                                this.getClass().getResource("/images/lightbulb.png"))));
                // Perform other actions here!
            } else {
                checkBox.setIcon(new ImageIcon(
                        Objects.requireNonNull(
                                this.getClass().getResource("/images/lightbulb_off.png"))));
                // Perform other actions here!
            }
        });

        getContentPane().add(checkBoxA);
        getContentPane().add(checkBoxB);
        getContentPane().add(checkBoxC);
    }

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

Swing JCheckBox Demo

How do I associate JLabel component with a JTextField?

In this example we associate a JLabel component with JTextField and JPasswordField using the setLabelFor(). A mnemonic need to be set for the JLabel component and when we press the defined key (ALT + U or ALT + P) a text field will be gained focus.

package org.kodejava.swing;

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

public class JLabelSetForTextField extends JFrame {
    public JLabelSetForTextField() throws HeadlessException {
        initialize();
    }

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

        JLabel usernameLabel = new JLabel("Username: ");
        JLabel passwordLabel = new JLabel("Password: ");
        JTextField usernameField = new JTextField(20);
        JPasswordField passwordField = new JPasswordField(20);

        // To make the association between the JLabel and JTextField or
        // JPasswordField we need to define the displayed mnemonic and then
        // call JLabel's setLabelFor method.
        usernameLabel.setDisplayedMnemonic(KeyEvent.VK_U);
        usernameLabel.setLabelFor(usernameField);
        passwordLabel.setDisplayedMnemonic(KeyEvent.VK_P);
        passwordLabel.setLabelFor(passwordField);

        getContentPane().add(usernameLabel);
        getContentPane().add(usernameField);
        getContentPane().add(passwordLabel);
        getContentPane().add(passwordField);
    }

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

How do I create JLabel with an image icon?

To create a JLabel with an image icon we can either pass an ImageIcon as a second parameter to the JLabel constructor or use the JLabel.setIcon() method to set the icon.

package org.kodejava.swing;

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

public class JLabelWithIcon extends JFrame {
    public JLabelWithIcon() throws HeadlessException {
        initialize();
    }

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

        Icon userIcon = new ImageIcon(
                Objects.requireNonNull(this.getClass().getResource("/images/user.png")));
        JLabel userLabel = new JLabel("Full Name :", userIcon, JLabel.LEFT);

        final ImageIcon houseIcon = new ImageIcon(
                Objects.requireNonNull(this.getClass().getResource("/images/house.png")));
        JLabel label2 = new JLabel("Address :", JLabel.LEFT);
        label2.setIcon(houseIcon);

        getContentPane().add(userLabel);
        getContentPane().add(label2);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JLabelWithIcon().setVisible(true));
    }
}
JLabel witch Image Icon

JLabel witch Image Icon

How do I create JLabel component?

package org.kodejava.swing;

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

public class JLabelDemo extends JFrame {
    public JLabelDemo() throws HeadlessException {
        initialize();
    }

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

        // Create some JLabel with Texts and define the horizontal alignment
        JLabel label1 = new JLabel("Username :", JLabel.RIGHT);
        JLabel label2 = new JLabel("Password :", JLabel.RIGHT);
        JLabel label3 = new JLabel("Confirm Password :", JLabel.RIGHT);
        JLabel label4 = new JLabel("Remember Me!", JLabel.LEFT);
        JLabel label5 = new JLabel("Hello, Anybody There?", JLabel.CENTER);

        // Set the vertical alignment for label5 and also set a tool tip for it
        label5.setVerticalAlignment(JLabel.TOP);
        label5.setToolTipText("I have a tool tip with me!");

        getContentPane().add(label1);
        getContentPane().add(label2);
        getContentPane().add(label3);
        getContentPane().add(label4);
        getContentPane().add(label5);
    }

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

How do I create a message dialog box?

This example demonstrate how to create a message dialog box using the JOptionPane class methods. In the code below you’ll see the use of JOptionPane.showMessageDialog(), JOptionPane.showInputDialog() and JOptionPane.showConfirmDialog().

package org.kodejava.swing;

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

public class MessageDialogDemo extends JFrame {
    public MessageDialogDemo() throws HeadlessException {
        initialize();
    }

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

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

        JButton button1 = new JButton("Click Me!");
        button1.addActionListener(e -> {
            // Show a message dialog with a text message
            JOptionPane.showMessageDialog((Component) e.getSource(),
                    "Thank you!");
        });

        JButton button2 = new JButton("What is your name?");
        button2.addActionListener(e -> {
            // Show an input dialog that will ask you to input some texts
            String text = JOptionPane.showInputDialog((Component) e.getSource(),
                    "What is your name?");
            if (text != null && !text.equals("")) {
                JOptionPane.showMessageDialog((Component) e.getSource(),
                        "Hello " + text);
            }
        });

        JButton button3 = new JButton("Close Application");
        button3.addActionListener(e -> {
            // Show a confirmation dialog which will ask to for a YES or NO
            // button.
            int result = JOptionPane.showConfirmDialog((Component) e.getSource(),
                    "Are you sure want to close this application?");
            if (result == JOptionPane.YES_OPTION) {
                System.exit(0);
            } else if (result == JOptionPane.NO_OPTION) {
                // Do nothing, continue to run the application
            }
        });

        setLayout(new FlowLayout(FlowLayout.CENTER));
        getContentPane().add(button1);
        getContentPane().add(button2);
        getContentPane().add(button3);
    }
}
Message Dialog Box with JOptionPane

Message Dialog Box with JOptionPane