I have extended JPanel and overriden the paint method in order to draw some extra lines between the locations of certain JButtons within the panel. However, the lines are only drawn correctly when the gui is maximized, otherwise they are drawn at totally the wrong offset.
To paint the line I am using (‘rootNode’ and ‘child’ are both JButton, g is the Graphics parameter of the overriden paint method):
Point sourcePoint = new Point(rootNode.getLocation());
Point destPoint = new Point(child.getLocation());
SwingUtilities.convertPointToScreen(sourcePoint, rootNode.getParent());
SwingUtilities.convertPointToScreen(destPoint, child.getParent());
g.drawLine(sourcePoint.x, sourcePoint.y, destPoint.x, destPoint.y);
Picture of incorrect lines when not maximised: http://postimage.org/image/ws0yo9chf/
Picture of correct when maximised: http://postimage.org/image/fq84m5xmb/
Just to cover off on the comments. I don’t think you want to convert to screen coordinates in this case.
The
Graphicscontext for thepaintComponent(...)method will most likely be set up for the component coordinate system.JavaDoc for
Graphics.drawLine(...)states:Unless you’ve done something to change it via
Graphics.translate(...)orGraphics2D.setTransform(...), the coordinate system will be set up for the component.Apart from being in the wrong place, converting to screen coordinates will have the effect of changing the location of the lines depending on where the window is on the screen 🙂