May 2000
Beginner
726 pages
21h 42m
English
We have explored quite a few features of Java with the first three
versions of the
HelloJava application. But until now,
our application has been rather passive; it has waited patiently for
events to come its way and responded to the whims of the user. Now
our application is going to take some
initiative—HelloJava4 will blink! Here is
the code for our latest version:
//file: HelloJava4.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloJava4 extends JComponent implements MouseMotionListener, ActionListener, Runnable { // Coordinates for the message int messageX = 125, messageY = 95; String theMessage; JButton theButton; int colorIndex; // Current index into someColors. static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; boolean blinkState; public HelloJava4(String message) { theMessage = message; theButton = new JButton("Change Color"); setLayout(new FlowLayout( )); add(theButton); theButton.addActionListener(this); addMouseMotionListener(this); Thread t = new Thread(this); t.start( ); } public void paintComponent(Graphics g) { g.setColor(blinkState ? getBackground() : currentColor( )); g.drawString(theMessage, messageX, messageY); } public void mouseDragged(MouseEvent e) { messageX = e.getX( ); messageY = e.getY( ); repaint( ); } public void mouseMoved(MouseEvent e) {} public void actionPerformed(ActionEvent e) { // Did somebody push our button? if (e.getSource( ) == ...Read now
Unlock full access