Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

HelloJava4: Netscape’s Revenge

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.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class HelloJava4
    {
      public static void main( String[] args ) {
        JFrame frame = new JFrame( "HelloJava4" );
        frame.add( new HelloComponent4("Hello, Java!") );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize( 300, 300 );
        frame.setVisible( true );
      }
    }

    class HelloComponent4 extends JComponent
        implements MouseMotionListener, ActionListener, Runnable
    {
      String theMessage;
      int messageX = 125, messageY = 95; // Coordinates of the message

      JButton theButton;

      int colorIndex; // Current index into someColors.
      static Color[] someColors = {
        Color.black, Color.red, Color.green, Color.blue, Color.magenta };

      boolean blinkState;


      public HelloComponent4( 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content