0

When I add some white text on a black JTextPane the font color is inhomogeneous, resulting in blurry effect. If i use drawString in the same JTextPane the text is well painted. Changing ANTIALIASING does not resolve the problem.

The code is just a simple example of my issue, this is what i get:

enter image description here

Thanks to all

public final class Example extends JTextPane {

    public static void main(String... aArgs){
        new Example();
    }

    Example() {
        JFrame mainFrame= new JFrame(); 
        mainFrame.setSize(200,200);
        mainFrame.getContentPane().setLayout(new BorderLayout());
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setVisible(true);
        setBackground(Color.black);

        StyledDocument doc = getStyledDocument();
        Style style = addStyle("I'm a Style", null);
        StyleConstants.setForeground(style, Color.white);
        StyleConstants.setFontFamily(style,"Courier New");
        StyleConstants.setFontSize(style, 20);

        try { doc.insertString(doc.getLength(), "   Example1",style); }
        catch (BadLocationException e){}

        mainFrame.getContentPane().add(this);
    }

    public void paintComponent(Graphics g) {
        Graphics2D graphics2d = (Graphics2D) g;
        graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        super.paintComponent(graphics2d);

        graphics2d.setColor(Color.white);
        Font courier = new Font("Courier New",0,20);
        graphics2d.setFont(courier.deriveFont(20));
        graphics2d.drawString("   Example2", 0, 150);
    }

}
Ondra K.
  • 2,767
  • 4
  • 23
  • 39
Lamaresh
  • 11
  • 1

1 Answers1

0

I found a solution how to make JTextPane paint anti-aliased font?

I had to add to JTextPane

putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, null);

and had to remove both RenderingHints.KEY_ANTIALIASING and RenderingHints.KEY_TEXT_ANTIALIASING

Lamaresh
  • 11
  • 1
  • Did you notice that that answer is from 2010 and that there is a comment to that answer saying that it doesn't work in JDK 9? That's because class `SwingUtilities2` is in package `sun.swing`, which is not accessible by default in JDK 9 and above. In fact the _javadoc_ for class `SwingUtilities2` states: "While this class is public, it should not be treated as public API and its API may change in incompatable ways between dot dot releases and even patch releases. You should not rely on this class even existing." – Abra May 01 '19 at 21:05