且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-22 21:41:08

突出显示文本后,JTextArea不再停留在底部.

Once you highglight the text, the JTextArea does not stick to the bottom anymore.

问题在于,仅当插入标记位于文档末尾时,才会自动滚动.

The problem is that automatic scrolling will only happen when the caret is at the end of the Document.

突出显示文字严格来说不是问题.问题是用户在文本区域中的任意位置单击鼠标,因为这会更改插入符号的位置.

Highlighting text isn't strictly the problem. The problem is the user clicking the mouse anywhere in the text area since that will change the caret position.

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

So if you want automatic scrolling to always be enabled the proper solution would be to remove the MouseListener and MouseMouseMotionListener from the text area to prevent all mouse related activity.

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

Or as a simple hack you could always reset the caret position of the Document:

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

让我们假设您有多个具有相同功能的文本区域.您无需为每个文本区域创建自定义侦听器.可以共享侦听器.该代码可以写为:

Lets assume you have multiple text areas to have the same functionality. You don't need to create a custom listener for each text area. The listener can be shared. The code could be written as:

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