How to disable the ability to highlight in JTextArea

风流意气都作罢 提交于 2021-01-29 16:38:49

问题


I am looking for a way to disable the ability to highlight in the JTextArea.

Currently this is my 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);

I use the DefaultCaret class to always have the JTextArea viewpoint pushed to the bottom at all times and textArea1.setEditable(false) to stop end users being able to type anything in.

However, if I highlight text the DefaultCaret method just stops working. Once you highglight the text, the JTextArea does not stick to the bottom anymore.


回答1:


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.

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

Edit:

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


来源:https://stackoverflow.com/questions/62448636/how-to-disable-the-ability-to-highlight-in-jtextarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!