Swing/AutomaticallyCloseDialog のバックアップの現在との差分(No.11)
- category: swing folder: AutomaticallyCloseDialog title: JOptionPaneを自動的に閉じる tags: [JOptionPane, Timer, HierarchyListener, JLabel] author: aterai pubdate: 2013-09-02T00:27:47+09:00 description: JOptionPaneにカウントダウンと自動クローズを行うためのJLabelを追加します。 image:
概要
JOptionPane
にカウントダウンと自動クローズを行うためのJLabel
を追加します。
Screenshot
Advertisement
サンプルコード
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();
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;
// private int countdown = SECONDS;
@Override public void actionPerformed(ActionEvent e) {
//int i = --countdown;
// 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
-
HierarchyListener
を使って、JLabel
の表示状態の変化を監視 -
HierarchyListener
を使用してJLabel
の表示状態の変化を監視
-
javax.swing.Timer
- 親の
JOptionPane
が表示されてJLabel#isShowing()
がtrue
になったら、Timer#start()
でカウントダウンを開始 - 親の
JOptionPane
が表示されてJLabel#isShowing()
がtrue
になったらTimer#start()
でカウントダウンを開始 - 指定した時間が経過したら
Window#dispose()
メソッドを使用して、親のJOptionPane
を自動的に閉じる-
Window#dispose()
を使うので、JOptionPane.showConfirmDialog(...)
の戻り値はJOptionPane.CLOSED_OPTION
になる
-
- 指定した時間が経過したら
Window#dispose()
メソッドを使用して親のJOptionPane
を自動的に閉じる-
Window#dispose()
を使用するのでJOptionPane.showConfirmDialog(...)
の戻り値はJOptionPane.CLOSED_OPTION
になる
-
- 親の
参考リンク
- JComponentの表示状態
- JOptionPaneのデフォルトフォーカス
- swing - Java: How to continuously update JLabel which uses atomicInteger to countdown after ActionListener - Stack Overflow