Setting Tab Policy in Swing JTextPane

I want my JTextPane to insert spaces when I press Tab. It currently inserts a tab character (ASCII 9).

Do I need to tweak the JTextPane's tab policy at all (other than capturing "tab-key" events and inserting spaces, it seems a)?

+1


source to share


3 answers


You can set javax.swing.text.Document on your JTextPane. The following example will give you an idea of ​​what I mean :)

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;

public class Tester {

    public static void main(String[] args) {
        JTextPane textpane = new JTextPane();
        textpane.setDocument(new TabDocument());
        JFrame frame = new JFrame();
        frame.getContentPane().add(textpane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(200, 200));
        frame.setVisible(true);
    }

    static class TabDocument extends DefaultStyledDocument {
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            str = str.replaceAll("\t", " ");
            super.insertString(offs, str, a);
        }
    }
}

      



Define a DefaultStyleDocument file to do the job. Then set the document to your JTextPane.

Cheers Kai

+5


source


As far as I know, you have to catch key events as you say. Depending on your usage, you can also get away with waiting until the input is entered and changing the tabs to spaces at this time.



0


source


You can try subclassing the DefaultStyledDocument and overriding the insertion to replace any tabs in the inserted elements with spaces. Then set your subclass to the JTextPane using setStyledDocument (). This can be more of a problem than catching key events.

0


source







All Articles