Question

How do I minimize and restore frames and JFrames?

Answer

This question stumped me when I first took a look at it. There is no minimize or restore method in JFrame, or java.awt.Frame for that matter. However, I knew there had to be a way - as JFrames frequently need to be restored programmatically. I suspected that the problem was a difference in terminology, and after a little searching, found the answer.

JFrame inherits the setState method from java.awt.Frame. This method allows you to change the state of a window from "iconified", back to "normal". This is, in actual fact, minimize and restore - but the documentation uses different terms. To minimize or restore a window, we simply call the setState method, and pass it a state parameter to indicate whether we want to minimize or restore the window..

For example, to minimize a Frame (or subclass, such as JFrame), we pass the 'iconified' parameter

myFrame.setState ( Frame.ICONIFIED );

To restore the frame to its normal state, we call the setState method with the 'normal' parameter

myFrame.setState ( Frame.NORMAL );

To demonstrate this effect, I've written a small demonstration, which you can compile and run. In the following example, a new frame is created, and then minimized. After a short delay, it is restored again.

import java.awt.*;

public class FrameTest
{
        public static void main (String args[]) throws Exception
        {
                // Create a test frame
                Frame frame = new Frame("Hello");
                frame.add ( new Label("Minimize demo") );
                frame.pack();

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

                // Sleep for 5 seconds, then minimize
                Thread.sleep (5000);
                frame.setState ( Frame.ICONIFIED );

                // Sleep for 5 seconds, then restore
                Thread.sleep (5000);
                frame.setState ( Frame.NORMAL );

                // Sleep for 5 seconds, then kill window
                Thread.sleep (5000);
                frame.setVisible (false);
                frame.dispose();

                // Terminate test
                System.exit(0);
        }
}


Back