问题
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