Disable editing in a JTextPane while allowing visible cursor movement

爷,独闯天下 提交于 2019-12-12 11:23:25

问题


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?


回答1:


Extend your DocumentFilter introducing flag isAPI. If it's false prevent all the changes. When you need to add content programmatically set the flag, add the content, and reset the flag back to false.




回答2:


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!




回答3:


This did the trick for me (a combination of the previous suggestions):

textPane.addFocusListener(new FocusListener() {

    @Override
    public void focusGained(FocusEvent e) {
         textPane.getCaret().setVisible(true);
    }
});



回答4:


This is probably a dirty, dirty hack, but I got this to work.

After you have set the text pane to un-editable, use textPane.getCaret().setVisible(true) to re-enable the caret



来源:https://stackoverflow.com/questions/12700607/disable-editing-in-a-jtextpane-while-allowing-visible-cursor-movement

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