Swing/AutomaticallyCloseDialog のバックアップ(No.2)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/AutomaticallyCloseDialog へ行く。
- 1 (2013-09-06 (金) 12:43:30)
- 2 (2013-09-06 (金) 15:58:55)
- 3 (2014-05-31 (土) 21:42:59)
- 4 (2014-10-28 (火) 03:15:21)
- 5 (2015-01-09 (金) 12:08:38)
- 6 (2016-04-21 (木) 15:31:42)
- 7 (2017-02-10 (金) 15:00:02)
- 8 (2017-04-07 (金) 13:51:51)
- 9 (2017-12-24 (日) 15:18:23)
- 10 (2018-02-05 (月) 19:10:58)
- 11 (2020-01-31 (金) 15:05:47)
- 12 (2021-07-25 (日) 23:20:46)
- 13 (2025-01-03 (金) 08:57:02)
- 14 (2025-01-03 (金) 09:01:23)
- 15 (2025-01-03 (金) 09:02:38)
- 16 (2025-01-03 (金) 09:03:21)
- 17 (2025-01-03 (金) 09:04:02)
- 18 (2025-06-19 (木) 12:41:37)
- 19 (2025-06-19 (木) 12:43:47)
TITLE:JOptionPaneを自動的に閉じる
Posted by aterai at 2013-09-02
JOptionPaneを自動的に閉じる
`JOptionPane
にカウントダウンと自動クローズを行うための
JLabel
`を追加します。
- &jnlp;
- &jar;
- &zip;
サンプルコード
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
`- `
HierarchyListener
を使って、
JLabel
`の表示状態の変化を監視
- `
- `
javax.swing.Timer
`- `
JLabel
の表示状態の変化し、
JLabel#isShowing()
が
true
となって親の
JOptionPane
が表示されたら、
Timer#start()
`でカウントダウンを開始 - 指定した時間が経過したら、`
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