I use a JTextArea
where using double click I can able to select the word at any place but I don't want to enable edit. Which means text can be entered only at the end of text area and not anywhere in between.
I have tried with mouse listeners like below:
@Override
public void mouseClicked(MouseEvent me) {
if(SwingUtilities.isLeftMouseButton(me)){
System.err.println("clicked");
int pos = textArea.getCaretPosition();
if(pos < textArea.getDocument().getLength()){
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
}
This makes double click not to select the word. I understand it is because caret position is moved to end. But how can I achieve this?
Check out the Protected Text Component which allows you to protect multiple areas of a Document from change.
Or if you don't need to be able to "select" any of the protected text than a simpler solution is to use a NavigationFilter:
Okay, this is slightly hacky...
Basically what this does is installs a "protected"
DocumentFilter
, which will only allow input to put in from a certain point in theDocument
.It overrides the
JTextArea
'sinsert-break
key binding (Enter) and records a marker. The "protected"DocumentFilter
then ensures that the content does not precede this pointI was forced to implement a
KeyListener
on the field to move the cursor to the end of the input, while theDocumentFilter
was capable of handling this, it did present some issues with deleting and general usability. This also ensures that the selection is un-highlighted when new content is added...This is just an example, you're going to need to play with it and tweak it to meet your own needs....