See test below - the issue occurs with Java 11 EA17 on Windows OS. The font metrics object is modified by calling g2.rotate(...).
Test-----------------------------
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class RotationTest extends JFrame{
public static void main(String[] args){
SwingUtilities.invokeLater(() -> new RotationTest());
}
public RotationTest(){
setLayout(new FlowLayout());
JLabel l = new JLabel("123") {
@Override
protected void paintComponent(Graphics g)
{
Rectangle textRect = new Rectangle();
textRect.setBounds(0, 0, getWidth(), getHeight());
Graphics2D g2 = (Graphics2D)g;
double origin = (textRect.width-textRect.height)/2;
g2.translate(origin, origin);
FontMetrics fm1 = g.getFontMetrics();
g2.rotate(Math.toRadians(90), textRect.x+textRect.width/2, textRect.y+textRect.height/2);
FontMetrics fm2 = g.getFontMetrics();
assert fm1.getAscent() == fm2.getAscent();
super.paintComponent(g2);
g2.rotate(-Math.toRadians(90), textRect.x+textRect.width/2, textRect.y+textRect.height/2);
g2.translate(-origin, -origin);
}
};
add(l);
setTitle(this.getClass().getSimpleName());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setVisible(true);
}
}
Test-----------------------------
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class RotationTest extends JFrame{
public static void main(String[] args){
SwingUtilities.invokeLater(() -> new RotationTest());
}
public RotationTest(){
setLayout(new FlowLayout());
JLabel l = new JLabel("123") {
@Override
protected void paintComponent(Graphics g)
{
Rectangle textRect = new Rectangle();
textRect.setBounds(0, 0, getWidth(), getHeight());
Graphics2D g2 = (Graphics2D)g;
double origin = (textRect.width-textRect.height)/2;
g2.translate(origin, origin);
FontMetrics fm1 = g.getFontMetrics();
g2.rotate(Math.toRadians(90), textRect.x+textRect.width/2, textRect.y+textRect.height/2);
FontMetrics fm2 = g.getFontMetrics();
assert fm1.getAscent() == fm2.getAscent();
super.paintComponent(g2);
g2.rotate(-Math.toRadians(90), textRect.x+textRect.width/2, textRect.y+textRect.height/2);
g2.translate(-origin, -origin);
}
};
add(l);
setTitle(this.getClass().getSimpleName());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setVisible(true);
}
}
- duplicates
-
JDK-8139178 Wrong fontMetrics when printing in Landscape (OpenJDK)
- Resolved
- relates to
-
JDK-8213985 Graphics2D.getFontMetrics().getStringBounds(...).getBounds() gets modified after applying Graphics2D.rotate(...) transform
- Open