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

HelloJava3: The Button Strikes!

Now we can move on to some fun stuff. HelloJava3 brings us a new graphical interface component: JButton.[4] In this example, we add a JButton component to our application that changes the color of our text each time the button is pressed. The draggable-message capability is still there, too. Our new code looks like this:

    //file: HelloJava3.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class HelloJava3
    {

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

    class HelloComponent3 extends JComponent
        implements MouseMotionListener, ActionListener
    {
      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 };

      public HelloComponent3( String message ) {
        theMessage = message;
        theButton = new JButton("Change Color");
        setLayout( new FlowLayout() );
        add( theButton );
        theButton.addActionListener( this );
        addMouseMotionListener( this );
      }

      public void paintComponent( Graphics g ) {
        g.drawString( theMessage, messageX, messageY );
      }

      public void mouseDragged( MouseEvent e ) {
        messageX = e.getX();
        messageY = e.getY();
        repaint();
      }

      public void mouseMoved( MouseEvent ...
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