TITLE:JOptionPaneを自動的に閉じる

Posted by at 2013-09-02

JOptionPaneを自動的に閉じる

`JOptionPaneにカウントダウンと自動クローズを行うためのJLabel`を追加します。

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

サンプルコード

label.addHierarchyListener(new HierarchyListener() {
  private Timer timer = null;
  private AtomicInteger atomicDown = new AtomicInteger(SECONDS);
  @Override public void hierarchyChanged(HierarchyEvent e) {
    final JLabel l = (JLabel)e.getComponent();
    if((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED)!=0) {
      if(l.isShowing()) {
        textArea.append("isShowing=ture\n");
        atomicDown.set(SECONDS);
        l.setText(String.format("Closing in %d seconds", SECONDS));
        timer = new Timer(1000, new ActionListener() {
          //private int countdown = SECONDS;
          @Override public void actionPerformed(ActionEvent e) {
            //int i = --countdown;
            int i = atomicDown.decrementAndGet();
            l.setText(String.format("Closing in %d seconds", i));
            if(i<=0) {
              Window w = SwingUtilities.getWindowAncestor(l);
              if(w!=null && timer!=null && timer.isRunning()) {
                textArea.append("Timer: timer.stop()\n");
                timer.stop();
                textArea.append("window.dispose()\n");
                w.dispose();
              }
            }
          }
        });
        timer.start();
      }else{
        textArea.append("isShowing=false\n");
        if(timer!=null && timer.isRunning()) {
          textArea.append("timer.stop()\n");
          timer.stop();
          timer = null;
        }
      }
    }
  }
});
View in GitHub: Java, Kotlin

解説

  • `java.awt.event.HierarchyListener`
  • `javax.swing.Timer`
    • `JLabelの表示状態の変化し、JLabel#isShowing()trueとなって親のJOptionPaneが表示されたら、Timer#start()`でカウントダウンを開始
    • 指定した時間が経過したら、`Window#dispose()を使って、親のJOptionPane`を自動的に閉じる
      • `Window#dispose()を使うので、JOptionPane.showConfirmDialog(...)の戻り値は、JOptionPane.CLOSED_OPTION`になる

参考リンク

コメント