3

我想知道是否有办法在 jeditorpane 中将制表符转换为空格,就像您在 IDE 中工作时看到的那样。我不想设置标签大小。我已经可以轻松做到了。

我想将制表符替换为空格中的等效项。因此,例如,如果我的制表符有 5 个空格长,我希望所有制表符在创建时立即替换为 5 个空格。

有任何想法吗?

4

1 回答 1

6

DocumentFilter在将AbstractDocument文本插入Document.

阅读 Swing 教程中有关文本组件功能的部分以获取更多信息。

简单的例子:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class TabToSpaceFilter extends DocumentFilter
{
    @Override
    public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
        throws BadLocationException
    {
        replace(fb, offset, 0, text, attributes);
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attributes)
        throws BadLocationException
    {
        //  In case someone tries to clear the Document by using setText(null)

        if (text == null)
            text = "";

        super.replace(fb, offset, length, text.replace("\t", "    "), attributes);
    }

    private static void createAndShowGUI()
    {
        JTextArea textArea = new JTextArea(5, 20);
        AbstractDocument doc = (AbstractDocument) textArea.getDocument();
        doc.setDocumentFilter( new TabToSpaceFilter() );

        JFrame frame = new JFrame("Integer Filter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout( new java.awt.GridBagLayout() );
        frame.add( new JScrollPane(textArea) );
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
    }

}
于 2010-06-23T16:34:39.743 回答