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.example.swing;

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

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

    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(200, 200);

        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent 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);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingFrameState().setVisible(true);
            }
        });
    }
}

How do I get the JFrame of a component?

This demo give an example on how to get the JFrame of a component. In this example we try to get the JFrame from a button action listener event. To get the JFrame we utilize the SwingUtilities.getRoot() method and this will return the root component of the component tree in out small program below which is a JFrame

Beside getting the JFrame, in this program we also do small stuff like changing the frame background color by a random color every time a user presses the Change Frame Color button.

package org.kodejava.example.swing;

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

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

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

        this.setLayout(new FlowLayout(FlowLayout.CENTER));

        final JLabel rLabel = new JLabel("r: ");
        final JLabel gLabel = new JLabel("g: ");
        final JLabel bLabel = new JLabel("b: ");

        JButton button = new JButton("Change Frame Background Color");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Component component = (Component) e.getSource();

                // Returns the root component for the current component tree
                JFrame frame = (JFrame) SwingUtilities.getRoot(component);

                int r = (int) (Math.random() * 255);
                int g = (int) (Math.random() * 255);
                int b = (int) (Math.random() * 255);

                rLabel.setText("r: " + r);
                gLabel.setText("g: " + g);
                bLabel.setText("b: " + b);

                frame.getContentPane().setBackground(new Color(r, g, b));
            }
        });

        this.getContentPane().add(button);
        this.getContentPane().add(rLabel);
        this.getContentPane().add(gLabel);
        this.getContentPane().add(bLabel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new GetFrameDemo().setVisible(true);
            }
        });
    }
}

How do I disable JFrame close button?

To disable the close operation on a JFrame, when user click the close icon on the JFrame, we can set the value of the default close operation to WindowConstants.DO_NOTHING_ON_CLOSE.

package org.kodejava.example.swing;

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

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

    private void initialize() {
        // WindowConstants.DO_NOTHING_ON_CLOSE tell JFrame instance to do
        // nothing when a window closing event occurs.
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

        JButton button = new JButton("Close");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        this.setLayout(new FlowLayout(FlowLayout.CENTER));
        this.setSize(new Dimension(100, 100));
        this.getContentPane().add(button);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DisableCloseButtonDemo().setVisible(true);
            }
        });
    }
}

How do I handle JFrame window events?

This example show you how to handle JFrame window events such as windowOpened, windowClosing, windowClosed, etc. For handling these events we need to add a WindowListener listener to the JFrame instance. Here we use the WindowAdapter abstract class and implement the method which event we want to handle.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class WindowListenerDemo extends JFrame {
    public WindowListenerDemo() {
        initializeComponent();
    }

    private void initializeComponent() {
        setSize(300, 300);
        setTitle("Window Listener");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        this.addWindowListener(new WindowAdapter() {
            // Invoked when a window has been opened.
            public void windowOpened(WindowEvent e) {
                System.out.println("Window Opened Event");
            }

            // Invoked when a window is in the process of being closed.
            // The close operation can be overridden at this point.
            public void windowClosing(WindowEvent e) {
                System.out.println("Window Closing Event");
            }

            // Invoked when a window has been closed.
            public void windowClosed(WindowEvent e) {
                System.out.println("Window Close Event");
            }

            // Invoked when a window is iconified.
            public void windowIconified(WindowEvent e) {
                System.out.println("Window Iconified Event");
            }

            // Invoked when a window is de-iconified.
            public void windowDeiconified(WindowEvent e) {
                System.out.println("Window Deiconified Event");
            }

            // Invoked when a window is activated.
            public void windowActivated(WindowEvent e) {
                System.out.println("Window Activated Event");
            }

            // Invoked when a window is de-activated.
            public void windowDeactivated(WindowEvent e) {
                System.out.println("Window Deactivated Event");
            }

            // Invoked when a window state is changed.
            public void windowStateChanged(WindowEvent e) {
                System.out.println("Window State Changed Event");
            }

            // Invoked when the Window is set to be the focused Window, which means
            // that the Window, or one of its sub components, will receive keyboard
            // events.
            public void windowGainedFocus(WindowEvent e) {
                System.out.println("Window Gained Focus Event");
            }

            // Invoked when the Window is no longer the focused Window, which means
            // that keyboard events will no longer be delivered to the Window or any of
            // its sub components.
            public void windowLostFocus(WindowEvent e) {
                System.out.println("Window Lost Focus Event");
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new WindowListenerDemo().setVisible(true);
            }
        });
    }
}

How do I create undecorated frame?

This code give you an example of how to create a frame without the title bar and the frame icons such as maximize, minimize and close.

package org.kodejava.example.swing;

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

public class UndecoratedFrame {
    private static Point point = new Point();

    public static void main(String[] args) {
        final JFrame frame = new JFrame();

        // Disables or enables decorations for this frame. By setting undecorated
        // to true will remove the frame's title bar including the maximize,
        // minimize and the close icon.
        frame.setUndecorated(true);

        // As the the frame's title bar removed we need to close out frame for
        // instance using our own button.
        JButton button = new JButton("Close Me");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        // The mouse listener and mouse motion listener we add here is to simply
        // make our frame dragable.
        frame.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                point.x = e.getX();
                point.y = e.getY();
            }
        });
        frame.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                Point p = frame.getLocation();
                frame.setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
            }
        });

        frame.setSize(300, 300);
        frame.setLocation(200, 200);
        frame.setLayout(new BorderLayout());

        frame.getContentPane().add(button, BorderLayout.NORTH);
        frame.getContentPane().add(new JLabel("Drag Me", JLabel.CENTER), BorderLayout.CENTER);
        frame.setVisible(true);
    }
}

How do I change JFrame image icon?

This example demonstrate how to change a JFrame image icon using the setIconImage() method.

package org.kodejava.example.swing;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class FrameIconExample extends JFrame {
    public static void main(String[] args) {
        FrameIconExample frame = new FrameIconExample();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Set the window size and its title
        frame.setSize(new Dimension(250, 250));
        frame.setTitle("Frame Icon Example");

        // Read the image that will be used as the application icon.
        // Using "/" in front of the image file name will locate the
        // image at the root folder of our application. If you don't
        // use a "/" then the image file should be on the same folder
        // with your class file.
        try {
            URL resource = frame.getClass().getResource("/logo.png");
            BufferedImage image = ImageIO.read(resource);
            frame.setIconImage(image);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Display the form
        frame.setVisible(true);
    }
}

How do I handle a window closing event in Swing?

Here you will see how to handle the window closing event of a JFrame. What you need to do is implement a java.awt.event.WindowListener interface and call the frame addWindowListener() method to add the listener to the frame instance. To handle the closing event implements the windowClosing() method of the interface.

But, instead of implementing the java.awt.event.WindowListener interface which require us to implement the entire methods defined in the interface, we can create a an instance of WindowAdapter object and override only the method we need, which is the windowsClosing() method. Let’s see the code snippet below.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class WindowClosingDemo extends JFrame {
    public static void main(String[] args) {
        WindowClosingDemo frame = new WindowClosingDemo();
        frame.setSize(new Dimension(250, 250));
        frame.add(new Button("Hello World"));

        // Add window listener by implementing WindowAdapter class to
        // the frame instance. To handle the close event we just need
        // to implement the windowClosing() method.
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("WindowClosingDemo.windowClosing");
                System.exit(0);
            }
        });

        // Show the frame
        frame.setVisible(true);
    }
}

How do I close a JFrame application?

Closing a JFrame application can be done by setting the default close operation of the frame. There are some defined constant for the default operation. These constants defined in the javax.swing.WindowConstants interface includes EXIT_ON_CLOSE, HIDE_ON_CLOSE, DO_NOTHING_ON_CLOSE and DISPOSE_ON_CLOSE.

To exit an application we can set it to EXIT_ON_CLOSE, this option will call the System.exit() method when user initiate a close operation on the frame.

package org.kodejava.example.swing;

import javax.swing.*;

public class MainFrameClose extends JFrame {
    public static void main(String[] args) {
        MainFrameClose frame = new MainFrameClose();
        frame.setSize(250, 250);

        // Be defining the default close operation of a JFrame to
        // EXIT_ON_CLOSE the application will be exited by calling
        // System.exit() when user initiate a close event on the
        // frame.
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

How do I change the cursor shape in Swing?

Using the following example you can change the shape of mouse cursor in your Java Swing desktop application. The cursor is represented by the java.awt.Cursor class. Create an instance of Cursor using the new operator and pass the cursor type to the Cursor class constructor.

We can change Swing objects (JLabel, JTextArea, JButton, etc) cursor using the setCursor() method. In the snippet below, for demonstration, we change the cursor of the JFrame. When your mouse pointer/cursor positioned inside the frame the shape will be changed.

A collections of cursor shapes defined in the java.awt.Cursor class, such as:

  • Cursor.DEFAULT_CURSOR
  • Cursor.HAND_CURSOR
  • Cursor.CROSSHAIR_CURSOR
  • Cursor.WAIT_CURSOR
  • etc
package org.kodejava.example.swing;

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

public class ChangeCursorDemo extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ChangeCursorDemo frame = new ChangeCursorDemo();
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setSize(250, 250);

                // Here we create a hand shaped cursor!
                Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
                frame.setCursor(cursor);
                frame.setVisible(true);
            }
        });
    }
}

How do I make a centered JFrame?

If you have a JFrame in your Java Swing application and want to center its position on the screen you can use the following examples.

The first way is to utilize java.awt.Toolkit class to get the screen size. The getScreenSize() method return a java.awt.Dimension from where we can get the width and height of the screen. Having this values in hand we can calculate the top left position of our JFrame as shown in step 2 of the code below.

package org.kodejava.example.swing;

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

public class CenteredJFrame extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                // Get the size of the screen
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

                CenteredJFrame frame = new CenteredJFrame();
                frame.setTitle("Centered JFrame");
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setSize(250, 250);

                // Calculates the position where the CenteredJFrame
                // should be paced on the screen.
                int x = (screenSize.width - frame.getWidth()) / 2;
                int y = (screenSize.height - frame.getHeight()) / 2;
                frame.setLocation(x, y);
                frame.setVisible(true);
            }
        });
    }
}

The second example which is better and simpler is to use the setLocationRelativeTo(Component) method. According to the Javadoc of this method: If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

If you call the JFrame.pack() method. The method should be called before the setLocationRelativeTo() method.

So we can rewrite the code above like this:

package org.kodejava.example.swing;

import javax.swing.*;

public class CenteredJFrameSecond {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenteredJFrame frame = new CenteredJFrame();
                frame.setTitle("Centered JFrame");
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setSize(250, 250);

                // Place the window in the center of the screen.
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}