Java Reference
In-Depth Information
Display 18.2
A Window Listener
(part 2 of 3)
44 setLayout(
new
BorderLayout());
45 JLabel confirmLabel =
new
JLabel(
46 "Are you sure you want to exit?");
47 add(confirmLabel, BorderLayout.CENTER);
48 JPanel buttonPanel =
new
JPanel();
49 buttonPanel.setBackground(Color.ORANGE);
50 buttonPanel.setLayout(
new
FlowLayout());
51 JButton exitButton =
new
JButton("Yes");
52 exitButton.addActionListener(
this
);
53 buttonPanel.add(exitButton);
54 JButton cancelButton =
new
JButton("No");
55 cancelButton.addActionListener(
this
);
56 buttonPanel.add(cancelButton);
57 add(buttonPanel, BorderLayout.SOUTH);
58 }
59
public void
actionPerformed(ActionEvent e)
60 {
61 String actionCommand = e.getActionCommand();
62
if
(actionCommand.equals("Yes"))
63 System.exit(0);
64
else if
(actionCommand.equals("No"))
65 dispose();
//Destroys only the ConfirmWindow
.
66
else
67 System.out.println(
"Unexpected Error in Confirm Window.");
68 }
69 }
//End of inner class ConfirmWindow
70
71
public static void
main(String[] args)
72 {
73 WindowListenerDemo demoWindow =
new
WindowListenerDemo();
74 demoWindow.setVisible(
true
);
75 }
76
77
public
WindowListenerDemo()
78 {
79 setSize(WIDTH, HEIGHT);
80 setTitle("Window Listener Demonstration");
81
82 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
83 addWindowListener(
new
CheckOnExit());
84
85 getContentPane().setBackground(Color.LIGHT_GRAY);
86 JLabel aLabel =
new
JLabel(
"I like to be sure you are sincere.");
87 add(aLabel);
88 }
89 }
Even if you have a window listener,
you normally must still invoke
setDefaultCloseOperation.