/** * TypeableWindow illustrates the KeyListener interface. * * 0. Run the TypeableWindowTester. Type r, g, b, or any other key that * you care to type. What happens? * * 1. Note that TypeableWindow is a subclass of MainWindow, just as * PaintedWindow is. That means that you can have a paint method. * Take a look at the constructor. Does it call the MainWindow constructor * to set the window title? (Hint: no.) What does it do instead? * * 2. TypeableWindow "implements" the "KeyListener interface." This is * a lot like being a subclass of a class, but it's a bit different. The * most important thing to remember about interfaces is that they *require* * you to write a particular collection of methods. The KeyListener, for * example, requires you to write the keyTyped, keyPressed, and keyReleased * methods, even if they don't do anything at all. * * 3. What's the difference between keyTyped, keyPressed, and keyReleased? * Move the code out of keyTyped and into keyReleased and re-run the program. * How does the behavior of the program change? Now move it to keyPressed. * What happens? * * 4. Take a look at Sun's documentation on the KeyListener interface. (Note * that in the list of classes, KeyListener is italicized--that's because it's * an interface and not a class.) What does the documentation say about the * difference between keyPressed and keyTyped? * * 5. There's a "switch" statement in keyTyped. What does this statement do? * When you get the chance, you should read in your textbook about switch statements. * * @author Jeff Ondich * @version 1/31/03 */ import java.awt.*; import java.awt.event.*; import javabook.*; public class TypeableWindow extends MainWindow implements KeyListener { private Color color; public TypeableWindow( String title ) { // Arrange for mouse events to be sent to this window. addKeyListener( this ); // Initialize the window. setSize( 500, 600 ); setLocation( 520, 20 ); setTitle( title ); setBackground( Color.white ); toFront(); setVisible( true ); } public void paint( Graphics g ) { Rectangle r = getBounds(); g.setColor( color ); g.fillOval( r.width / 4, r.height / 4, r.width / 2, r.height / 2 ); } public void keyTyped( KeyEvent e ) { switch( e.getKeyChar() ) { case 'r': color = Color.red; break; case 'b': color = Color.blue; break; default: color = Color.green; break; } repaint(); } public void keyPressed( KeyEvent e ) { } public void keyReleased( KeyEvent e ) { } }