Java - 显示最小化的JFrame窗口

时间:2011-12-13 12:08:15

标签: java swing jframe focus

如果JFrame窗口最小化,有没有办法让它重新聚焦?

我试图让它点击某个点,然后恢复它。

            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));
            }

2 个答案:

答案 0 :(得分:12)

如果您想从iconified恢复,可以将其状态设置为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);

来自here

的示例

每当状态发生变化时都会触发WindowEvents和处理这些触发器的WindowListener接口。在这种情况下,您可以使用:

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

如果您想要检查另一个程序的状态更改,则不存在“纯Java”解决方案,只需要获取窗口ID即可。

答案 1 :(得分:5)

您可以将状态设置为正常:

frame.setState(NORMAL);

完整示例:

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();
    }

}