TITLE:JPopupMenuなどからWindowを閉じる

Posted by at 2013-03-11

JPopupMenuなどからWindowを閉じる

`JPopupMenuや、JToolBarなどに親Windowを閉じるためのAction`を作成します。

  • &jnlp;
  • &jar;
  • &zip;
WindowClosingAction.png

サンプルコード

private static class ExitAction extends AbstractAction{
  public ExitAction() {
    super("Exit");
  }
  @Override public void actionPerformed(ActionEvent e) {
    JComponent c = (JComponent)e.getSource();
    Window window = null;
    Container parent = c.getParent();
    if(parent instanceof JPopupMenu) {
      JPopupMenu popup = (JPopupMenu)parent;
      JComponent invoker = (JComponent)popup.getInvoker();
      window = SwingUtilities.getWindowAncestor(invoker);
    }else if(parent instanceof JToolBar) {
      JToolBar toolbar = (JToolBar)parent;
      if(((BasicToolBarUI)toolbar.getUI()).isFloating()) {
        window = SwingUtilities.getWindowAncestor(toolbar).getOwner();
      }else{
        window = SwingUtilities.getWindowAncestor(toolbar);
      }
    }else{
      JComponent invoker = (JComponent)c.getParent();
      window = SwingUtilities.getWindowAncestor(invoker);
    }
    if(window!=null) {
      //window.dispose();
      window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));
    }
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、親となる`JFrameを取得し、window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));`を 使って、終了イベントを実行しています。

  • `JPopupMenu`
    • `JPopupMenu#getInvoker()を使って、JComponent#setComponentPopupMenu(popup)で設定したコンポーネントを取得し、SwingUtilities.getWindowAncestor(...)で、親Window`を取得
  • `JMenuBar`
    • `SwingUtilities.getWindowAncestor(...)で、自身の親Window`を取得
  • `JToolBar`
    • 移動中の場合、`JComponent#setComponentPopupMenu(toolbar)で取得した移動中のWindowの親WindowをWindow#getOwner()`で取得
    • 移動中では無い場合、`SwingUtilities.getWindowAncestor(toolbar)で、自身の親Window`を取得

参考リンク

コメント