在Swing的JTextPane中设置选项卡策略

Ita*_*man 1 java swing jtextpane

每当我按Tab键时,我希望我的JTextPane插入空格.目前它插入制表符(ASCII 9).

反正是有自定义JTextPane的选项卡策略(除了捕获"tab-key"事件和插入空格本身似乎)?

Kai*_*hel 5

您可以在JTextPane上设置javax.swing.text.Document.以下示例将让您了解我的意思:)

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

定义DefaultStyleDocument来完成工作.然后将Document设置为JTextPane.

干杯凯