May 2000
Beginner
726 pages
21h 42m
English
Let’s make our application a little more interactive, shall we?
The following improvement, HelloJava2
, allows us to drag the
message around with the mouse.
HelloJava2 is a new application—another
subclass of the JComponent class. In that sense,
it’s a sibling of HelloJava1. Having just
seen inheritance at work, you might wonder why we aren’t
creating a subclass of HelloJava1 and exploiting
inheritance to build upon our previous example and extend its
functionality. Well, in this case, that would not necessarily be an
advantage, and for clarity we simply start over.[8]
Here is HelloJava2:
//file: HelloJava2.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloJava2 extends JComponent implements MouseMotionListener { // Coordinates for the message int messageX = 125, messageY = 95; String theMessage; public HelloJava2(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) {} public static void main(String[] args) { JFrame f = new JFrame("HelloJava2"); // Make the application exit when the window is closed. f.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent we) { System.exit(0); } }); f.setSize(300, 300); ...Read now
Unlock full access