如何使 JTextPane 在 Java 中具有不同的制表符大小?

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

我有一个 JTextPane,但我注意到如果我使用 .setText(),所有选项卡都会被删除。
为了解决这个问题,我看到了两个选项:

  1. 正确设置选项卡。
  2. 用 html 特殊字符   替换所有选项卡,然后更改 JTextPane 中的选项卡大小以匹配 html 选项卡的宽度。

我不知道#1 怎么做,所以我尝试使用粗略的技巧#2。 所以我的问题是,如何使用 HTMLDocument 更改 JTextPane 的标签大小,或者如何 setText() 而不删除标签?

我还使用 getText()setText() 来将文本保存在 JTextPane 中。

提前致谢。

为了在没有方法 1 或 2 的情况下解决我的问题,我这样做了:

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();
        }
    }
});

我发现这会覆盖默认的标签输入。