JOptionPaneを自動的に閉じる
Total: 9956, Today: 1, Yesterday: 3
Posted by aterai at 
Last-modified: 
Summary
JOptionPaneにカウントダウンと自動クローズを行うためのJLabelを追加します。
Screenshot

Advertisement
Source Code Examples
label.addHierarchyListener(new HierarchyListener() {
  private Timer timer = null;
  private AtomicInteger atomicDown = new AtomicInteger(SECONDS);
  @Override public void hierarchyChanged(HierarchyEvent e) {
    JLabel l = (JLabel) e.getComponent();
    if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
      if (l.isShowing()) {
        textArea.append("isShowing=true\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, KotlinDescription
java.awt.event.HierarchyListenerHierarchyListenerを使用してJLabelの表示状態の変化を監視
javax.swing.Timer- 親の
JOptionPaneが表示されてJLabel#isShowing()がtrueになったらTimer#start()でカウントダウンを開始 - 指定した時間が経過したら
Window#dispose()メソッドを使用して親のJOptionPaneを自動的に閉じるWindow#dispose()を使用するのでJOptionPane.showConfirmDialog(...)の戻り値はJOptionPane.CLOSED_OPTIONになる
 
- 親の
 
Reference
- JComponentの表示状態
 - JOptionPaneのデフォルトフォーカス
 - swing - Java: How to continuously update JLabel which uses atomicInteger to countdown after ActionListener - Stack Overflow