WindowWatcher.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
A short example of a WindowListener trapping window events.
*/
class WindowWatcher extends JFrame
{
public static void main(String argv[])
{
WindowWatcher f = new WindowWatcher();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.show();
}
public WindowWatcher()
{
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension ss = kit.getScreenSize();
setSize(ss.width/3,ss.height/6);
setLocation(ss.width/4,ss.height/4);
setTitle("CISC370-011 -- window events");
ButtonPanel sp = new ButtonPanel();
Container contentPane = getContentPane();
contentPane.add(sp);
addWindowListener(new Eh());
}
class Eh implements WindowListener {
public void windowOpened(WindowEvent e)
{ System.out.println("Opened."); }
public void windowClosing(WindowEvent e)
{ System.out.println("Closing."); }
public void windowClosed(WindowEvent e)
{ System.out.println("Closed."); }
public void windowIconified(WindowEvent e)
{ System.out.println("Iconified."); }
public void windowDeiconified(WindowEvent e)
{ System.out.println("Deiconified."); }
public void windowActivated(WindowEvent e)
{ System.out.println("Activated."); }
public void windowDeactivated(WindowEvent e)
{ System.out.println("Deactivated."); }
}
}
class ButtonPanel extends JPanel
{
public ButtonPanel() {
mkButton("Red",Color.RED);
mkButton("Yellow",Color.YELLOW);
mkButton("Green",Color.GREEN);
}
void mkButton(String name,final Color bg) {
JButton jb = new JButton(name);
add(jb);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ setBackground(bg); }
});
}
}