Graphics Context misaligned on first paint

The AffineTransform associated with the graphics context passed to paintComponent() is not always the identity transform. For reasons that aren’t clear, the m12 entry has the value 38.0 initially and after resizing the enclosing frame. Trivially, one can modify the copy supplied by g.create().

Graphics2D g2d = (Graphics2D) g.create();
AffineTransform at = g2d.getTransform();
at.translate(originX, originY);
g2d.setTransform(at);
g2d.scale(scale, scale);
g2d.rotate(Math.toRadians(angle), 0, 0);
g2d.fillRect(xOffset, yOffset, rectWidth, rectHeight);
g2d.dispose();

Addendum: As @MadProgrammer observes, “If I remove the controls from the GUI, it appears … in the center.” Indeed, the observed horizontal offset is precisely the preferred width of the slider in BorderLayout.WEST. I suspect that the origin is adjusted after a resize to meet the Component#paintAll() contract more easily: “The origin of the graphics context, its (0, 0) coordinate point, is the top-left corner of this component.”

Leave a Comment