Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable editing in a JTextPane while allowing visible cursor movement

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?

like image 782
Gigatron Avatar asked Dec 04 '22 14:12

Gigatron


1 Answers

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!

like image 127
Bruno Vieira Avatar answered Feb 19 '23 11:02

Bruno Vieira