Setting the tab policy in Swing's JTextPane

社会主义新天地 提交于 2019-12-02 09:08:02

问题


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 (other than catching "tab-key" events and inserting the spaces myself seems an)?


回答1:


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




回答2:


As far as I know, you'd have to catch key events, as you say. Depending on usage, you might also get away with waiting until the input is submitted, and changing tabs to spaces at that time.




回答3:


You could try sub-classing DefaultStyledDocument and overriding insert to replace any tabs in the inserted elements with spaces. Then install your sub-class in JTextPane with setStyledDocument(). This may be more trouble than catching key events though.



来源:https://stackoverflow.com/questions/363784/setting-the-tab-policy-in-swings-jtextpane

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