In Java 8, if I set a JTextPane's width to match the value returned by FontMetrics.stringWidth, the text fits exactly and is drawn on one line. But, in Java 17, with the same code, the last word in the text is wrapped. Here's my code:
import java.awt.*;
import javax.swing.*;
public class SimpleTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(SimpleTest::test);
}
private static void test() {
Test test = new Test();
JPanel panel = new JPanel(new BorderLayout());
panel.add(test);
JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class Test extends JComponent {
private static final long serialVersionUID = 1L;
private JTextPane textPane;
private Test() {
textPane = new JTextPane();
textPane.setFont(new Font("Arial", Font.BOLD, 24));
textPane.setBorder(null);
textPane.setContentType("text/plain");
}
@Override
protected void paintComponent(Graphics g) {
String labelText = "THIS IS A TEST";
textPane.setText(labelText);
textPane.setLocation(new Point(0, 0));
FontMetrics fm = textPane.getFontMetrics(textPane.getFont());
int width = fm.stringWidth(labelText);
int height = fm.getHeight();
textPane.setSize(width, height);
Graphics2D g2D = (Graphics2D) g.create(0, 0, width, height * 2);
textPane.paint(g2D);
g2D.dispose();
}
}
}
Is it possible to make the behavior consistent?