/** * ClickableWindow illustrates the MouseListener interface. * * 0. Run the ClickableWindowTester. Click to your heart's content. * * 1. Read the code. Where does the message that appears on screen come from? * How is the message text printed to screen? * * 2. 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? * * 3. Take a look at Sun's documentation on the MouseListener interface. Experiment * with the various required methods (mouseReleased, etc.) to see if you can * make them get called. * * @author Jeff Ondich * @version 2/24/05 */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ClickableWindow extends JFrame implements MouseListener { private int paintCount; private int x; private int y; private String message; public ClickableWindow( String title, String mess ) { // Arrange for mouse events to be sent to this window. addMouseListener( this ); // Initialize the window. setSize( 500, 600 ); setLocation( 20, 20 ); setTitle( title ); setBackground( Color.red ); toFront(); setVisible( true ); // Initialize the text location and message. x = 200; y = 100; message = mess; paintCount = 0; } public void paint( Graphics g ) { paintCount++; System.out.println( "paint" + paintCount ); g.clearRect( 0, 0, getWidth(), getHeight() ); g.drawString( message, x, y ); } public void mousePressed( MouseEvent e ) { } public void mouseReleased( MouseEvent e ) { x = e.getX(); y = e.getY(); repaint(); } public void mouseClicked( MouseEvent e ) { } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mouseDragged( MouseEvent e ) { } public static void main( String[] args ) { ClickableWindow window = new ClickableWindow( "This is clickable", "Ouch" ); // Arrange for the program to shut down when you close the window. window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } }