JFrameの複数作成と終了
Total: 28805
, Today: 1
, Yesterday: 0
Posted by aterai at
Last-modified:
Summary
JFrame
を複数作成し、これらをすべて閉じた時にアプリケーションを終了します。
Screenshot

Advertisement
Source Code Examples
private static int number = 0;
public static JFrame createFrame(String title) {
JFrame frame = new JFrame((title == null) ? "Frame #" + number : title);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
number++;
// frame.addWindowListener(new WindowAdapter() {
// @Override public void windowClosing(WindowEvent e) {
// number--;
// if (number == 0) {
// JFrame f = (JFrame) e.getSource();
// f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// }
// }
// });
return frame;
}
View in GitHub: Java, KotlinExplanation
上記のサンプルでは、すべてのJFrame
にsetDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
を設定しているため、Java VM
内で最後の表示可能なWindow
が破棄されるとVM
が終了します。
- When DISPOSE_ON_CLOSE met WebStartによると、
Web Start
で実行する場合はDISPOSE_ON_CLOSE
ではなくEXIT_ON_CLOSE
を使っておいた方が良さそう?- 上記のサンプルでは解説とは異なりコメントアウトしたコードで終了するよう変更している