我希望我的JTextPane每次按Tab时都插入空格。当前,它会插入制表符(ASCII 9)。

无论如何,有没有自定义JTextPane的选项卡策略(除了捕获“ tab-key”事件并自己插入空格外)?

最佳答案

您可以在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);
        }
    }
}


定义一个DefaultStyleDocument来完成这项工作。然后将Document设置为您的JTextPane。

干杯

关于java - 在Swing的JTextPane中设置标签策略,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/363784/

10-11 22:37