Sunday 28 February 2016

HelloJava2: The Sequel

Now that we’ve got some basics down, let’s make our application a little more interactive. The following minor upgrade allows us to drag the message text around with the mouse. We’ll call this example HelloJava2 rather than cause confusion by continuing to expand the old one, but the primary changes here and further on lie in adding capabilities to the HelloComponent class and simply making the corresponding changes to the names to keep them straight (e.g., HelloComponent2, HelloComponent3, and so on). Having just seen inheritance at work, you might wonder why we aren’t creating a subclass of HelloComponent and exploiting inheritance to build upon our previous example and extend its functionality. Well, in this case, that would not provide much advantage, and for clarity we simply start over. Here is HelloJava2:

 import java.awt.*;  
 import java.awt.event.*;  
 import javax.swing.*;  
 public class HelloJava2  
 {  
 public static void main( String[] args ) {  
 JFrame frame = new JFrame( "HelloJava2" );  
 frame.add( new HelloComponent2("Hello, Java!") );  
 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );  
 frame.setSize( 300, 300 );  
 frame.setVisible( true );  
 }  
 }  
 class HelloComponent2 extends JComponent  
 implements MouseMotionListener  
 {  
 String theMessage;  
 int messageX = 125, messageY = 95; // Coordinates of the message  
 public HelloComponent2( String message ) {  
 theMessage = message;  
 addMouseMotionListener(this);  
 }  
 public void paintComponent( Graphics g ) {  
 g.drawString( theMessage, messageX, messageY );  
 }  
 public void mouseDragged(MouseEvent e) {  
 // Save the mouse coordinates and paint the message.  
 messageX = e.getX();  
 messageY = e.getY();  
 repaint();  
 }  
 public void mouseMoved(MouseEvent e) { }  
 }  
Two slashes in a row indicate that the rest of the line is a comment. We’ve added a few comments to HelloJava2 to help you keep track of everything. Place the text of this example in a file called HelloJava2.java and compile it as before. You should get new class files, HelloJava2.class and HelloComponent2.class, as a result. Run the example using the following command:
 C:\> java HelloJava2
Or, if you are following in Eclipse, click the Run button. Feel free to substitute your own salacious comment for the “Hello, Java!” message and enjoy many hours of fun, dragging the text around with your mouse. Notice that now when you click the window’s close button, the application exits; we’ll explain that later when we talk about events. Now let’s see what’s changed.

0 comments:

Post a Comment