I’m working on a custom Swing Component for my application, and I started drawing things with the public void paintComponent(Graphics g). Everything works fine except for the fact that I can’t draw any rectangles. I think the problem is with the getX() and getY() part, but I don’t know that for sure. Here’s my code:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (mouseEntered) {
g.setColor(HIGHLIGHTED_COLOR);
} else {
g.setColor(BACKGROUND_COLOR);
}
g.fillRect(getX(), getY(), getWidth(), getHeight());
//Draw rest of stuff (works fine)
The API says that it is supposed to be used like this: g.fillRect(x, y, width, height), and that’s what I’m doing.
The rest of the drawing works perfectly, but I can’t figure out why this isn’t drawing. Any suggestions?
I’m not exactly sure how your Component is defined, but the default value for a Component‘s
getX()method is the X coordinate of the Component‘s upper left hand corner (relative to the root Component).When you are drawing in a Component‘s
paintComponent(Graphics)method in Swing, the origin of the Graphics context that you are drawing to is typically located at the top-left of the Component itself, not the root Component.So by doing this call:
You are likely drawing the rectangle outside of the clip bounds of the Component!
(e.g. if the Component is located at 100, 100 and it has a width of 20 and height of 20, the rectangle you are drawing, in absolute coordinates, is at
(200, 200)to(220, 220))If you want to draw a rectangle that encompasses the entire component, you may want to try something more like this:
This will draw from the origin (again, likely the top-left hand corner of the Component) down to the width and height of the component.
(Using previous example: Component is at 100, 100, and width/height of 20, the rectangle this would draw is at
(100, 100)to(120, 120))Hope this helps =)