Java - Show a minimized JFrame window

11,506

Solution 1

If you want to bring it back from being iconified, you can just set its state to normal:

JFrame frame = new JFrame(...);
// Show the frame
frame.setVisible(true);

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

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

Example from here.

There are also WindowEvents that are triggered whenever the state is changed and a WindowListener interface that handles these triggers.In this case, you might use:

public class YourClass implements WindowListener {
  ...
  public void windowDeiconified(WindowEvent e) {
    // Do something when the window is restored
  }
}

If you are wanting to check another program's state change, there isn't a "pure Java" solution, but just requires getting the window's ID.

Solution 2

You can set the state to normal:

frame.setState(NORMAL);

Full example:

public class FrameTest extends JFrame {

    public FrameTest() {
        final JFrame miniFrame = new JFrame();
        final JButton miniButton = new JButton(
          new AbstractAction("Minimize me") {
            public void actionPerformed(ActionEvent e) {
                miniFrame.setState(ICONIFIED);
            }
        }); 

        miniFrame.add(miniButton);
        miniFrame.pack();
        miniFrame.setVisible(true);

        add(new JButton(new AbstractAction("Open") {
            public void actionPerformed(ActionEvent e) {
                miniFrame.setState(NORMAL);
                miniFrame.toFront();
                miniButton.requestFocusInWindow();
            }
        }));

        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new FrameTest();
    }

}
Share:
11,506
Stripies
Author by

Stripies

Updated on August 05, 2022

Comments

  • Stripies
    Stripies almost 2 years

    If a JFrame window is minimized, is there any way to bring it back to focus?

    I am trying to get it to click a certain point, then restore it.

                while (isRunning) {
                    start = System.currentTimeMillis();
                    frame.setState(Frame.ICONIFIED);
                    robot.mouseMove(clickX, clickY);
                    robot.mousePress(InputEvent.BUTTON1_MASK);
                    frame.setState(Frame.NORMAL);
                    Thread.sleep(clickMs - (System.currentTimeMillis() - start));
                }
    
  • Stripies
    Stripies over 12 years
    I tried that just for testing, and it worked. But when I implemented it into my actual program, it doesn't work.
  • Jon Egeland
    Jon Egeland over 12 years
    If you post your code in the question, we can modify it to make it work.
  • Jonas
    Jonas over 12 years
    @AndrewThompson: Good suggestions, I added them and a button for minimizing.