簡體   English   中英

Java - 無法將窗口帶到前面

[英]Java - cannot bring the window to front

我正在嘗試執行以下代碼:

SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                if (frame.getExtendedState() == Frame.ICONIFIED)
                                    frame.setExtendedState(Frame.NORMAL);
                                frame.getGlassPane().setVisible(!frame.getGlassPane().isVisible());

                                frame.toFront();
                                frame.repaint();

                            }
                        });

不幸的是,這並沒有把它從其他窗戶后面帶到前面......任何解決方案?

根據setExtendedState的API文檔:

如果框架當前在屏幕上可見(Window.isShowing()方法返回true), 開發人員應檢查通過WindowStateListener接收的WindowEvent的WindowEvent.getNewState()方法的返回值,以確定該狀態實際上是被改變了

如果在屏幕上看不到幀,則可能生成也可能不生成事件。 在這種情況下,開發人員可能會認為狀態在此方法返回后立即更改。 稍后,當調用setVisible(true)方法時,框架將嘗試應用此狀態。 在這種情況下,也不保證接收任何WindowEvent.WINDOW_STATE_CHANGED事件。

但是,還有一個windowDeiconified回調可以掛鈎到WindowListener

SwingUtilities.invokeLater(new Runnable() {
  private final WindowListener l = new WindowAdapter() {
    @Override
    public void void windowDeiconified(WindowEvent e) {
      // Window now deiconified so bring it to the front.
      bringToFront();

      // Remove "one-shot" WindowListener to prevent memory leak.
      frame.removeWindowListener(this);
    }
  };

  public void run() {
    if (frame.getExtendedState() == Frame.ICONIFIED) {
      // Add listener and await callback once window has been deiconified.
      frame.addWindowListener(l);
      frame.setExtendedState(Frame.NORMAL);
    } else {
      // Bring to front synchronously.
      bringToFront();
    }
  }

  private void bringToFront() {
    frame.getGlassPane().setVisible(!frame.getGlassPane().isVisible());
    frame.toFront();
    // Note: Calling repaint explicitly should not be necessary.
  }
});

我發現JDialog上的toFront()的以下解決方法適用於Windows 7(尚未測試其他平台):

boolean aot = dialog.isAlwaysOnTop();
dialog.setAlwaysOnTop(true);
dialog.setAlwaysOnTop(aot);

Paul van Bemmelen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM