Home > Enterprise >  JTextPane wraps text differently between Java 8 and Java 17
JTextPane wraps text differently between Java 8 and Java 17

Time:09-17

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();
        }

    }

}

Java 8: Java 8 Java 17: Java 17

Is it possible to make the behavior consistent?

CodePudding user response:

To get the width, call this:

int width = textPane.getPreferredSize().width;

Not this:

int width = fm.stringWidth(labelText);

CodePudding user response:

I don't know the specifics of it, but I'm 100% sure that in Java 8 the method fm.stringWidth(labelText) is 1 greater than it is in Java 11 because if I do fm.stringWidth(labelText) 1 then the line wrapping works. Just change that line, and your code will work.

Please let me know if this helps.

  • Related