June 2013
Beginner
1007 pages
33h 32m
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 been
completely event-driven, waiting patiently for
events to come its way and responding to the whims of the user. Now our
application is going to take some initiative—HelloJava4 will blink![5] Here is the code for our latest version:
//file: HelloJava4.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassHelloJava4{publicstaticvoidmain(String[]args){JFrameframe=newJFrame("HelloJava4");frame.add(newHelloComponent4("Hello, Java!"));frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(300,300);frame.setVisible(true);}}classHelloComponent4extendsJComponentimplementsMouseMotionListener,ActionListener,Runnable{StringtheMessage;intmessageX=125,messageY=95;// Coordinates of the messageJButtontheButton;intcolorIndex;// Current index into someColors.staticColor[]someColors={Color.black,Color.red,Color.green,Color.blue,Color.magenta};booleanblinkState;publicHelloComponent4(Stringmessage){theMessage=message;theButton=newJButton("Change Color");setLayout(newFlowLayout());add(theButton);theButton.addActionListener(this);addMouseMotionListener(this);Threadt=newThread(this);t.start();}publicvoidpaintComponent(Graphicsg){g.setColor(blinkState ...