How do I change JFrame state programmatically?

In the following code snippet you’ll learn how to programmatically change the frame state of a JFrame component in a Swing application. The JFrame states are represented as a bitwise masks. You can minimize, maximize or make the JFrame state to normal, using the JFrame.setExtendedState() method.

You can pass the following values as the parameter to the method:

  • Frame.NORMAL
  • Frame.ICONIFIED
  • Frame.MAXIMIZED_HORIZ
  • Frame.MAXIMIZED_VERT
  • Frame.MAXIMIZED_BOTH
package org.kodejava.swing;

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

public class SwingFrameState extends JFrame {
    public SwingFrameState() throws HeadlessException {
        initUI();
    }

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

    private void initUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        final JButton minimize = new JButton("Minimize");
        final JButton maximize = new JButton("Maximize");
        final JButton normal = new JButton("Normal");

        add(normal);
        add(minimize);
        add(maximize);

        pack();
        setSize(500, 200);

        ActionListener listener = e -> {
            if (e.getSource() == normal) {
                setExtendedState(Frame.NORMAL);
            } else if (e.getSource() == minimize) {
                setExtendedState(Frame.ICONIFIED);
            } else if (e.getSource() == maximize) {
                setExtendedState(Frame.MAXIMIZED_BOTH);
            }
        };

        minimize.addActionListener(listener);
        maximize.addActionListener(listener);
        normal.addActionListener(listener);
    }
}

The screenshot of the output from the code snippet above is:

Change JFrame State Programmatically

Change JFrame State Programmatically

How do I get the state of a thread?

To get the state of a thread use getState() method of a Thread class. One thing to be noted is that this method is designed for use in monitoring of the system state, not for synchronization control.

package org.kodejava.lang;

public class GetThreadState implements Runnable {
    public static void main(String[] args) {
        Thread thread = new Thread(new GetThreadState());
        thread.start();

        // Get the state of the thread.
        Thread.State state = thread.getState();
        System.out.println("State: " + state.name());
    }

    public void run() {
        System.out.println("Start..");
    }
}