// File: MoreComplexExample.java // Author: Rahul Simha // Date created: August 14, 1998 // Modified: Sept 2007 // // NOTE: // Illustrates advanced syntax/features of Java // Not commented import java.awt.*; import java.awt.event.*; public class MoreComplexExample extends Frame implements ActionListener { // Store current location of mouse int currentX=0, currentY=0; // Peculiarities of the Java GUI model -- listener objects public void createListeners () { this.addMouseListener ( new MouseAdapter () { public void mousePressed (MouseEvent m) { System.out.println ("mousePressed event: " + m.paramString()); int x = m.getX(); int y = m.getY(); Graphics g = MoreComplexExample.this.getGraphics(); g.drawLine (currentX, currentY, x, y); currentX = x; currentY = y; } } ); this.addMouseMotionListener ( new MouseMotionAdapter () { public void mouseDragged (MouseEvent m) { System.out.println ("mouseDragged event: " + m.paramString()); int x = m.getX(); int y = m.getY(); Graphics g = MoreComplexExample.this.getGraphics(); g.drawLine (currentX, currentY, x, y); currentX = x; currentY = y; } } ); } // Button-pressed events public void actionPerformed (ActionEvent a) { String eventDesc = a.getActionCommand(); System.out.println ("Button event: " + eventDesc); Color c = Color.gray; if (eventDesc.equalsIgnoreCase ("quit")) System.exit(0); else if (eventDesc.equalsIgnoreCase ("red")) c = Color.red; else if (eventDesc.equalsIgnoreCase ("blue")) c = Color.blue; else if (eventDesc.equalsIgnoreCase ("green")) c = Color.green; this.setBackground (c); this.repaint(); } // Test the code via a static function public static void test () { MoreComplexExample f = new MoreComplexExample (); FlowLayout fl = new FlowLayout(); f.setLayout (fl); Button qb = new Button ("Quit"); qb.addActionListener (f); f.add (qb); Button rb = new Button ("Red"); rb.addActionListener (f); f.add (rb); Button bb = new Button ("Blue"); bb.addActionListener (f); f.add (bb); Button gb = new Button ("Green"); gb.addActionListener (f); f.add (gb); f.createListeners (); f.setResizable (true); f.setSize (500,600); f.setVisible (true); } // To start execution, "main" is needed public static void main (String[] argv) { test (); } }