Setting the tab policy in Swing's JTextPane

后端 未结 3 1126
借酒劲吻你
借酒劲吻你 2021-01-22 10:25

I want my JTextPane to insert spaces whenever I press Tab. Currently it inserts the tab character (ASCII 9).

Is there anyway to customize the tab policy of JTextPane (o

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-22 11:27

    You can set a 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 to do the work. Then set the Document to your JTextPane.

    Cheers Kai

提交回复
热议问题