はい、 WindowListenerを使用してこれを行うことができます。
public void windowClosed(WindowEvent e) {
//This will only be seen on standard output.
displayMessage("WindowListener method called: windowClosed.");
}
public void windowOpened(WindowEvent e) {
displayMessage("WindowListener method called: windowOpened.");
}
public void windowIconified(WindowEvent e) {
displayMessage("WindowListener method called: windowIconified.");
}
public void windowDeiconified(WindowEvent e) {
displayMessage("WindowListener method called: windowDeiconified.");
}
public void windowActivated(WindowEvent e) {
displayMessage("WindowListener method called: windowActivated.");
}
public void windowDeactivated(WindowEvent e) {
displayMessage("WindowListener method called: windowDeactivated.");
}
public void windowGainedFocus(WindowEvent e) {
displayMessage("WindowFocusListener method called: windowGainedFocus.");
}
public void windowLostFocus(WindowEvent e) {
displayMessage("WindowFocusListener method called: windowLostFocus.");
}
public void windowStateChanged(WindowEvent e) {
displayStateMessage(
"WindowStateListener method called: windowStateChanged.", e);
詳細については、このチュートリアルを参照してください。
ただし、シナリオでは、アダプタークラスを使用することをお勧めします(必要なイベントは1つだけなので、疲れてすべてのメソッドを実装する必要はありません)。したがって、要件に応じた例を次に示します。
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class NoCloseFrame extends JFrame {
public static void main( String[] arg ) {
new NoCloseFrame();
}
public NoCloseFrame() {
super( "No Close Frame!" );
setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
setSize( 300, 300 );
setVisible( true );
addWindowListener( new AreYouSure() );
}
private class AreYouSure extends WindowAdapter {
public void windowClosing( WindowEvent e ) {
int option = JOptionPane.showOptionDialog(
NoCloseFrame.this,
"Are you sure you want to quit?",
"Exit Dialog", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE, null, null,
null );
if( option == JOptionPane.YES_OPTION ) {
System.exit( 0 );
}
}
}
}