// // HelloWeb3 applet example. // Source: _Exploring Java_, Niemeyer & Peck. // Modified by: B. Massingill. // // Description: // A HelloWeb3 applet displays an environment-selected message // and allows the user to drag it around with the mouse. // It also provides a "change color" button that, when clicked, // changes the color of the message, cycling through a // pre-defined list of colors. // // Usage: // Applet tag parameter "message" gives message to display. // Requires window sufficiently large to display selected // message, starting at position (125, 95). // Responds to click-and-drag operations on displayed messages. // Responds to button clicks. // import java.applet.Applet ; import java.awt.* ; import java.awt.event.* ; public class HelloWeb3 extends Applet implements MouseMotionListener, ActionListener { int messageX = 125, messageY = 95 ; String theMessage ; Button theButton ; int colorIndex = 0 ; static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta } ; // ---- overridden superclass methods -------------------------- // init: get message, set things up. public void init() { theMessage = getParameter("message") ; // create "change color" button theButton = new Button("Change Color") ; add(theButton) ; // set up to process mouse and button events addMouseMotionListener(this) ; theButton.addActionListener(this) ; } // paint: display message at current location. public void paint(Graphics gc) { gc.drawString(theMessage, messageX, messageY) ; } // ---- methods to handle mouse events ------------------------- // respond to "mouse dragged" events by changing location // of displayed message. public void mouseDragged(MouseEvent e) { messageX = e.getX() ; messageY = e.getY() ; repaint() ; } // ignore "mouse moved" events. public void mouseMoved(MouseEvent e) { } // ---- methods to handle button events ------------------------ // respond to click on "change color" button. public void actionPerformed(ActionEvent e) { if (e.getSource() == theButton) changeColor() ; } // ---- methods to set, obtain current color for message ------- // synchronized to avoid simultaneous access to colorIndex // by changeColor and currentColor. // changeColor: reset foreground color, repaint. synchronized private void changeColor() { if (++colorIndex == someColors.length) colorIndex = 0 ; setForeground(currentColor()) ; repaint() ; } synchronized private Color currentColor() { return someColors[colorIndex] ; } }