3

I want to set the size of a tab character, \t, in a JTextPane to be 4 spaces wide.

After Googling quite a bit I found some things that I will include here for what I have tried and maybe why they failed.

How do you set the tab size in a JEditorPane?

JTextPane is not a plain document.

Java JTextpane Tab Size

Eclipse raised some errors:

Type mismatch: cannot convert from javax.swing.text.AttributeSet to 
 javax.print.attribute.AttributeSet

and

The method setParagraphAttributes(javax.swing.text.AttributeSet, boolean) in the type JTextPane is not applicable for the 
 arguments (javax.print.attribute.AttributeSet, boolean)

http://www.java2s.com/Code/Java/Swing-JFC/TextPaneSample.htm

This page talks about styling with JTextPane. The code I adapted from it and made this:

MutableAttributeSet set = new SimpleAttributeSet(pane.getParagraphAttributes());
StyleConstants.setLeftIndent(set, 40);
StyleConstants.setRightIndent(set, 40);
Community
  • 1
  • 1
Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38
  • 1
    *"I want to set the size of an indent in a `JTextPane` to 4."* 4 what? Pixels, characters, ..fathoms? – Andrew Thompson Nov 05 '15 at 12:32
  • 1
    It is not clear to me what you mean by `indent`. Is this just the space between the edge of the TextPane and the actual text? If so, just set its Border to an EmptyBorder of the proper size. – FredK Nov 05 '15 at 15:45
  • I don't understand what "indent size" means to you. Typically indentation is the space from the left edge and you don't explain why the `setLeftIndent(...)` approach doesn't work. I would think that is the solution you should use. But then you also talk about tabbing, which is based on the data of the text pane, not the starting indentation of a row of text. – camickr Nov 05 '15 at 15:46
  • 1
    Are you sure that you didn't just import the wrong class ? You should have "import javax.swing.text.AttributeSet" instead of "import javax.print.attribute.AttributeSet" – Sharcoux Nov 05 '15 at 15:56
  • @FredK By indent I mean the size of a tab,"/t", character. – Moon Cheesez Nov 06 '15 at 00:08
  • @Sharcoux I just checked and I imported the right class, `import javax.swing.text.SimpleAttributeSet;` – Moon Cheesez Nov 06 '15 at 00:09
  • @camickr As just mentioned, by indent I mean a tab character or tabbing and I did not include why the approach failed as I did not know. – Moon Cheesez Nov 06 '15 at 00:14

2 Answers2

3

I want to set the size of a tab character, \t, in a JTextPane to be 4 spaces wide.

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

public class TextPaneTabs
{
    public static void setTabs( final JTextPane textPane, int charactersPerTab)
    {
        FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
//          int charWidth = fm.charWidth( 'w' );
        int charWidth = fm.charWidth( ' ' );
        int tabWidth = charWidth * charactersPerTab;
//      int tabWidth = 100;

        TabStop[] tabs = new TabStop[5];

        for (int j = 0; j < tabs.length; j++)
        {
            int tab = j + 1;
            tabs[j] = new TabStop( tab * tabWidth );
        }

        TabSet tabSet = new TabSet(tabs);
        SimpleAttributeSet attributes = new SimpleAttributeSet();
        StyleConstants.setTabSet(attributes, tabSet);
        int length = textPane.getDocument().getLength();
        textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
    }

    private static void createAndShowUI()
    {
        JTextPane textPane = new JTextPane();
        textPane.setText("12345678\n\t1\t2\t3aaaaa\t4\t5\t6\t7\t8\n\t1\t2\t3\t4\t5\t6\t7\t8\n\t\t12345678");
        JScrollPane scrollPane = new JScrollPane( textPane );
        scrollPane.setPreferredSize( new Dimension(700, 100 ) );

        // Change the tab size to 4 characters

        setTabs( textPane, 4 );

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( scrollPane );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

Of course when using the default Font of a JTextPane the width of a space is not very wide so the actual tab will not be that big.

camickr
  • 321,443
  • 19
  • 166
  • 288
2

From the link http://java-sl.com/tip_default_tabstop_size.html

import javax.swing.text.*;
import javax.swing.*;

public class TabSizeEditorKit extends StyledEditorKit {

    public static final int TAB_SIZE=36;

    public ViewFactory getViewFactory() {
        return new MyViewFactory();
    }

    static class MyViewFactory implements ViewFactory {

        public View create(Element elem) {
            String kind = elem.getName();
            if (kind != null) {
                if (kind.equals(AbstractDocument.ContentElementName)) {
                    return new LabelView(elem);
                } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                    return new CustomTabParagraphView(elem);
                } else if (kind.equals(AbstractDocument.SectionElementName)) {
                    return new BoxView(elem, View.Y_AXIS);
                } else if (kind.equals(StyleConstants.ComponentElementName)) {
                    return new ComponentView(elem);
                } else if (kind.equals(StyleConstants.IconElementName)) {
                    return new IconView(elem);
                }
            }

            return new LabelView(elem);
        }
    }

    public static void main(String[] args) {
        JFrame frame=new JFrame("Custom default Tab Size in EditorKit example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JEditorPane edit=new JEditorPane();
        edit.setEditorKit(new TabSizeEditorKit());
        try {
            edit.getDocument().insertString(0,"1\t2\t3\t4\t5", new SimpleAttributeSet());
        } catch (BadLocationException e) {
            e.printStackTrace(); 
        }
        frame.getContentPane().add(new JScrollPane(edit));

        frame.setSize(300,100);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }


    static class CustomTabParagraphView extends ParagraphView {

        public CustomTabParagraphView(Element elem) {
            super(elem);
        }

        public float nextTabStop(float x, int tabOffset) {
            TabSet tabs = getTabSet();
            if(tabs == null) {
                // a tab every 72 pixels.
                return (float)(getTabBase() + (((int)x / TAB_SIZE + 1) * TAB_SIZE));
            }

            return super.nextTabStop(x, tabOffset);
        }

    }
}
StanislavL
  • 56,971
  • 9
  • 68
  • 98