首页 > 解决方案 > JTextPane 中的字体颜色同质性问题

问题描述

当我在黑色 JTextPane 上添加一些白色文本时,字体颜色不均匀,导致效果模糊。如果我在同一个 JTextPane 中使用 drawString,则文本绘制得很好。更改 ANTIALIASING 并不能解决问题。

该代码只是我的问题的一个简单示例,这就是我得到的:

在此处输入图像描述

谢谢大家

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

}

标签: javaswing

解决方案


我找到了如何让 JTextPane 绘制抗锯齿字体的解决方案?

我不得不添加到 JTextPane

putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, null);

并且必须同时删除 RenderingHints.KEY_ANTIALIASING 和 RenderingHints.KEY_TEXT_ANTIALIASING


推荐阅读