Skip to content
Advertisement

JEditorPane – make tabs spaces

I’m wondering if there’s a way to have tabs convert to spaces in a jeditorpane, much like you’d see when working in an IDE. I don’t want to set the tab size. I can already do that easily.

I want to have tabs replaced with their equivalent in spaces. So for example if my tabs are 5 spaces long, I would want all tabs replaced immediately with 5 spaces whenever they are created.

Any ideas?

Advertisement

Answer

Add a DocumentFilter to the AbstractDocument to replaces tabs with spaces as text is inserted into the Document.

Read the section from the Swing tutorial on Text Component Features for more information.

Simple example:

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

}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement