key listener to the component, and 2) you must use the
mouseEntered method in a mouse listener to request the focus.
Rectangle rect; String label;Write a paintComponent method that accomplishes the following tasks:
public void paintComponent(Graphics gr) {
Graphics2D g = (Graphics2D)gr;
super.paintComponent(g);
FontMetrics fm = g.getFontMetrics(font);
// to get a boundary to appear properly over a filled object, you
// must first fill the object and then draw the boundary over it
g.setColor(Color.blue);
g.fill(rect);
g.setColor(Color.black);
g.draw(rect);
// In order to get the top of the string to be 10 pixels below the
// bottom of the rectangle, we must set the baseline to be 10 pixels
// plus the font's ascent below the bottom of the rectangle.
g.drawString(label, rect.getX() + rect.getWidth()/2 - fm.stringWidth(label) / 2,
rect.getY() + rect.getHeight() + 10 + fm.getAscent());
}
Here is some code to provide you context:
class Counter extends JPanel {
Rectangle rect;
String label;
// need a state variable to keep track of whether the mouse
// was last seen inside or outside the rectangle. It is helpful
// to use named constants to keep track of this state information.
final int OUTSIDE = 1;
final int INSIDE = 2;
int state = OUTSIDE;
int entered = 0; // counts number of times rect is entered
public Counter(Rectangle r, String l) {
rect = r;
label = l;
// we need to monitor the mouseMoved event in the
// MouseMotionListener. You might be tempted to use
// a MouseListenere and monitor the
// mouseEntered and mouseExited events, but these events
// do not work with custom
// graphics. They only apply to JComponents
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
if (rect.contains(e.getX(), e.getY())) {
// increment the entered counter only if the mouse
// was last seen outside the rectangle
if (state == OUTSIDE) {
state = INSIDE;
entered++;
}
}
else {
// else the mouse is outside the rectangle. If the mouse
// was last seen inside the rectangle, change the
// state to OUTSIDE
if (state == INSIDE)
state = OUTSIDE;
}
}
});
}