I have a JTextPane
which is populated by reading from a file, after which the data is parsed and formatted. The user is not allowed to edit the JTextPane
, but I want them to be able to navigate in it with a visible cursor.
If I use setEditable(false)
, the cursor is invisible, although it is possible to indirectly observe the position of the invisible cursor by holding down Shift and using the arrow keys to select a block of text.
To enable a visible cursor while disallowing editing, instead of setEditable(false)
I created a dummy DocumentFilter
that simply does nothing for its insertString()
, remove()
, and replace()
methods. But then I have to swap in a regular filter in order to programmatically populate the JTextPane
from a file, then put back the dummy filter right before returning control to the user.
So far this seems to work, but is there a simpler solution? If I leave this as is, is there any sequence of keystrokes or mouse activity that could somehow allow the user to edit the text pane, given that it is technically editable as per setEditable
?
textPane.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
textPane.setEditable(true);
}
@Override
public void focusGained(FocusEvent e) {
textPane.setEditable(false);
}
});
Yet another dirty hack! It seems to provide what you need!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With