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:
//file: HelloJava2.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassHelloJava2{publicstaticvoidmain(String[]args){JFrameframe=newJFrame("HelloJava2");frame.add(newHelloComponent2("Hello, Java!"));frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(300,300);frame.setVisible(true);}}classHelloComponent2extendsJComponentimplementsMouseMotionListener{StringtheMessage;intmessageX=125,messageY=95;// Coordinates of the messagepublicHelloComponent2(Stringmessage){theMessage=message;addMouseMotionListener(this);}publicvoidpaintComponent(Graphics
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.
Read now
Unlock full access