【问题标题】:How can I disable text highlighting for a JTextPane completely?如何完全禁用 JTextPane 的文本突出显示?
【发布时间】:2021-03-02 03:22:16
【问题描述】:

请有人告诉我如何禁用JTextPane 的文本突出显示。 我的JTextPane 是半透明的,因此突出显示的错误。但是没有突出显示是好的!

我尝试了以下方法:

DefaultHighlighter highlighter =  (DefaultHighlighter) chatTextPane.getHighlighter();
highlighter.removeAllHighlights();

chatTextPane.setHighlighter(null);

chatTextPane.setSelectedTextColor(new Color(0,0,0,0));
chatTextPane.setSelectionColor(new Color(0,0,0,0));

chatTextPane.setSelectionStart(0);
chatTextPane.setSelectionEnd(0);

chatTextPane.setCaret(new NoTextSelectionCaret(chatTextPane));
// with:
private class NoTextSelectionCaret extends DefaultCaret
{
    public NoTextSelectionCaret(JTextComponent textComponent)
    {
        setBlinkRate( textComponent.getCaret().getBlinkRate() );
        textComponent.setHighlighter( null );
    }

    @Override
    public int getMark()
    {
        return getDot();
    }
}

还有一些关于highlighter.getDrawsLayeredHighlights(); 的东西我什至不记得了。

谢谢!

【问题讨论】:

  • 您的意思是您不想让用户使用鼠标或键盘选择JTextPane 中的文本?换句话说,如果用户将鼠标拖过JTextPane 中的某些文本,那么该文本不会被突出显示?
  • 为什么不让突出显示与 jtextpane 背景颜色相同,这样您根本看不到它?
  • 我的 JTextPane 是半透明的 - 请参阅 Backgrounds With Transparency 了解可能的问题和一些解决方案。
  • @camickr 谢谢!我能弄明白
  • @Abra 这就是我的意思。我的问题是突出显示文本时出现的不良伪影

标签: java swing user-interface highlight jtextpane


【解决方案1】:

由于 Swing 的工作方式,突出显示显示了一些不受欢迎的伪影,我将 JTextPane 包裹在另一个具有透明颜色的面板中。

消除工件,将 JTextPane 包装在 AlphaContainer 中。

public class AlphaContainer extends JComponent
{
    private JComponent component;

    public AlphaContainer(JComponent component)
    {
        this.component = component;
        setLayout( new BorderLayout() );
        setOpaque( false );
        component.setOpaque( false );
        add( component );
    }

    /**
     *  Paint the background using the background Color of the
     *  contained component
     */
    @Override
    public void paintComponent(Graphics g)
    {
        g.setColor( component.getBackground() );
        g.fillRect(0, 0, getWidth(), getHeight());
    }
}

然后:

AlphaContainer ac = new AlphaContainer(chatTextPane);

并将 AlphaContainer 添加到您的框架中。如果 AlphaContainer 要包含在另一个组件中,请将另一个组件设置为 setOpaque(false);。

然后您可以根据需要设置chatTextPane.setHighlighter(null);,以禁用突出显示。

更多详细信息见camickr提供的Backgrounds With Transparency

【讨论】:

    猜你喜欢
    • 2011-08-06
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2015-06-10
    • 1970-01-01
    • 2010-10-24
    相关资源
    最近更新 更多