Java Reference
In-Depth Information
Creating the Rectangle object within the method call is more efficient because you don't
need to use the object anywhere else in the class. The following statements accomplish
the same thing in two steps:
Rectangle box = new Rectangle(buttonX, buttonY, 70, 20);
ok.setBounds(box);
The class has instance variables that hold the x,y position of the button, buttonX and
buttonY . They start out at 110,110 and change whenever the mouse comes within 50
pixels of the center of the button.
Mouse movements are tracked by implementing the MouseListener interface and its two
methods, mouseMoved( MouseEvent ) and mouseDragged( MouseEvent ) .
The panel uses mouseMoved() and ignores mouseDragged() .
When the mouse moves, a mouse event object's getX() and getY() methods return its
current x,y position, which is stored in the instance variables mouseX and mouseY .
The moveButton( int , int , int ) method takes three arguments:
The x or y position of the button
n
The x or y position of the mouse
n
The width or height of the panel
n
This method moves the button away from the mouse in either a vertical or horizontal
direction, depending on whether it is called with x coordinates and the panel height or y
coordinates and the width.
12
After the button's position has moved, the repaint() method is called, which causes the
panel's paintComponent( Graphics ) method to be called (lines 83-86).
Every component has a paintComponent() method that can be overridden to draw the
component. The button's setBounds() method displays it at the current x,y position
(line 85).
Window Events
Window events occur when a user opens or closes a window object, such as a JFrame or
a JWindow . Any component can generate these events, and a class must implement the
WindowListener interface to support them.
Search WWH ::




Custom Search