Swingexamples-responding-to-windows-event
提供:Dev Guides
Swingの例-ウィンドウのイベントへの応答
次の例は、Swingベースのアプリケーションでウィンドウのイベントに応答する方法を示しています。
ユーザーがフレームの閉じるボタンをクリックすると、次のオプションを使用できます。
- DO_NOTHING_ON_CLOSE -アクションなし。 windowClosingイベントをリッスンするだけで、さらにアクションを実行できます。
- HIDE_ON_CLOSE -これは、閉じるボタンがクリックされたときに非表示にするJFrameおよびJDialogのデフォルトの動作です。
- DISPOSE_ON_CLOSE -ウィンドウを非表示にして閉じ、ウィンドウで使用されていたリソースを解放します。
- EXIT_ON_CLOSE -System.exit(0)を使用してアプリケーションを終了します。
次の例は、 DO_NOTHING_ON_CLOSE の使用例を示しています。
例
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
});
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
panel.add(new JLabel("Hello World"));
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
出力
ウィンドウのデフォルトアイコンを変更 link:/cgi-bin/printpage.cgi [__ Print]