Search code examples
javajtextpane

How do I make a JTextPane have a different tab size in Java?


I have a JTextPane, but I have noticed that if I use .setText() all tabs get removed.
To fix this I see two options:

  1. Make the tabs get set properly.
  2. Replace all tabs with the html special character   and then change the tab size in the JTextPane to match the width of the html tab.

I do not know how to do #1 so I am trying to use the crude hack #2. So my question is, how do I change the tab size for JTextPane using an HTMLDocument, or how do I setText() and not have tabs be removed?

Also I am using getText() and setText() in order to save the text inside the JTextPane.

Thank you in advance.


Solution

  • In order to solve my problem without method 1 or 2 I have done this:

    textPane.getInputMap().put(KeyStroke.getKeyStroke("TAB"), "tab");
    textPane.getActionMap().put("tab", new AbstractAction("tab"){
        private static final long serialVersionUID = -2621537943352838927L;
    
        public void actionPerformed(ActionEvent e){
            try {
                textPane.getDocument().insertString(textPane.getCaretPosition(), " ", null);//The " " is the html special character (tab) in plain text.
            } catch (BadLocationException e1) {
                e1.printStackTrace();
            }
        }
    });
    

    I found that this overrides the default tab input.