Search code examples
javacursorjtextpane

Text cursor for JTextPane with HTML


I have the following problem: I want to change the cursor of a JTextPane with content type text/html to Cursor.TEXT_CURSOR. However, when setting setCursor(new Cursor(Cursor.TEXT_CURSOR)) it is ignored. I also tried to set the cursor in the mouse listener, but it is also directly changes back to the standard cursor. If the content type is text/plain, the cursor is by default the text cursor. Does any one has an idea how to reach this goal? I created an SCCEE to show this behavior:

import java.awt.Cursor;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;


public class TextPaneHtmlCursor extends JFrame {
    private JScrollPane jScrollPane1;
    private JTextPane jTextPane1;     

    public TextPaneHtmlCursor() {
        initComponents();
    }

    private void initComponents() {
        jScrollPane1 = new JScrollPane();
        jTextPane1 = new JTextPane();
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        jTextPane1.setContentType("text/html");
        jTextPane1.setCursor(new Cursor(Cursor.TEXT_CURSOR));
        jScrollPane1.setViewportView(jTextPane1);
        getContentPane().add(jScrollPane1);
        pack();
    }                    

    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TextPaneHtmlCursor().setVisible(true);
            }
        });
    }        
}

Thank you very much!


Solution

  • So after a little bit more digging, it would seem the the EditorKit (in this case HTMLEditorKit) is responsible for making the decisions about what cursor should be used.

    You can change the "default" cursor using something like...

    jTextPane1.setContentType("text/html");
    ((HTMLEditorKit)tp.getEditorKit()).setDefaultCursor(cursor);
    

    The default "default" is defined as private static final Cursor DefaultCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); which is very annoying...