Java Reference
In-Depth Information
The code places the buffered image onto a label as its icon, then stores the
buffered image into a panel that is placed inside the frame. We use this intermediate
panel to ensure that the background colors are set properly.
A more sophisticated version of
DrawingPanel
will also act as an event listener
for mouse events, so that as the user drags the mouse over the panel, the program
will display the cursor's (
x, y
) position on a status bar at the bottom for debugging.
To achieve this, the
DrawingPanel
can be modified to act as a mouse listener and
attach itself to listen to its central panel. Whenever the mouse moves, the mouse
listener will receive the event and will update the status bar text to show the mouse
position.
To implement these capabilities, we'll begin by changing our class header to the
following header:
public class DrawingPanel extends MouseInputAdapter {
We'll then add a new field called
statusBar
, of type
JLabel
, to the program
and place it in the south region of the frame. Initially the status bar's text will be
empty, but if the mouse moves, its listener will change the text to reflect the cur-
sor's position. The following code implements the mouse listener's
mouseMoved
method:
// draws status bar text when mouse moves
public void mouseMoved(MouseEvent e) {
statusBar.setText("(" + e.getX() + ", " + e.getY() + ")");
}
We'll also add the following code to the constructor to attach the
DrawingPanel
as a listener to its inner panel:
// attach listener to observe mouse movement
panel.addMouseListener(this);
panel.addMouseMotionListener(this);
There's another kind of event that we should handle in the
DrawingPanel
.
When the client code using
DrawingPanel
takes a long time (such as when it
uses console input to guide what shapes will be drawn), we may need to repaint
the
DrawingPanel
periodically to reflect any new shapes that the client has
drawn. To keep things simple, we don't want to force the client to call
repaint
itself.
To force the
DrawingPanel
to refresh at a given interval, we'll use a
Timer
to
periodically call
repaint
. Since a
Timer
requires an action listener as a parameter,
Search WWH ::
Custom Search