繁体   English   中英

如何禁用在 JTextArea 中突出显示的功能

[英]How to disable the ability to highlight in JTextArea

我正在寻找一种方法来禁用在 JTextArea 中突出显示的功能。

目前这是我的 JTextArea:

textArea1 = new JTextArea();
textArea1.setBorder(BorderFactory.createLineBorder(Color.black, 1));
DefaultCaret caret = (DefaultCaret) textArea1.getCaret(); // this line and the line below was inspired by a comment found here: https://stackoverflow.com/questions/15623287/how-to-always-scroll-to-bottom-of-text-area
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
textArea1.setEditable(false);
JScrollPane scrollPane1 = new JScrollPane(textArea1);

我使用 DefaultCaret class 始终将 JTextArea 视点推到底部,并textArea1.setEditable(false)阻止最终用户输入任何内容。

但是,如果我突出显示文本,DefaultCaret 方法就会停止工作。 突出显示文本后,JTextArea 不再粘在底部。

突出显示文本后,JTextArea 不再粘在底部。

问题是只有当插入符号位于文档末尾时才会发生自动滚动。

突出显示文本并不是严格意义上的问题。 问题是用户在文本区域的任意位置单击鼠标,因为这将更改插入符号 position。

因此,如果您希望始终启用自动滚动,正确的解决方案是从文本区域中删除MouseListenerMouseMouseMotionListener以防止所有与鼠标相关的活动。

或者作为一个简单的技巧,您可以随时重置文档的插入符号 position:

textArea.addMouseListener( new MouseAdapter()
{
    @Override
    public void mouseReleased(MouseEvent e)
    {
        JTextArea textArea = (JTextArea)e.getSource();
        textArea.setCaretPosition(textArea.getDocument().getLength());
    }
});

编辑:

假设您有多个文本区域具有相同的功能。 您不需要为每个文本区域创建自定义侦听器。 监听器可以共享。 代码可以写成:

    MouseListener ml = new new MouseAdapter()
    {
        @Override
        public void mouseReleased(MouseEvent e)
        {
            JTextArea textArea = (JTextArea)e.getSource();
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
    };

    textArea1.addMouseListener(ml);
    textArea2.addMouseListener(ml);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM