How do you set the tab size in a JEditorPane?
Asked Answered
D

3

9

A JTextArea's tab size can easily be set using setTabSize(int).

Is there a similar way to do it with a JEditorPane?

Right now, text with tabs in my pane looks like:

if (stuff){
            more stuff;
}

And, I'd prefer a much smaller tab stop:

if (stuff){
    more stuff;
}
Deform answered 16/4, 2009 at 19:28 Comment(1)
java-sl.com/tip_default_tabstop_size.html you can check thisKatz
D
12

As JEditorPane is designed to support different kinds of content types, it does not provide a way to specify a "tab size" directly, because the meaning of that should be defined by the content model. However when you use a model that's a PlainDocument or one of its descendants, there is a "tabSizeAttribute" that provides what you are looking for.

Example:

JEditorPane pane = new JEditorPane(...);
...
Document doc = pane.getDocument();
if (doc instanceof PlainDocument) {
    doc.putProperty(PlainDocument.tabSizeAttribute, 8);
}
...

From the Javadoc:

/**
 * Name of the attribute that specifies the tab
 * size for tabs contained in the content.  The
 * type for the value is Integer.
 */
public static final String tabSizeAttribute = "tabSize";
Depraved answered 16/4, 2009 at 19:48 Comment(2)
Thanks for not just a 'how', but a 'why' too!Deform
For Styled EditorKit it's also possible java-sl.com/tip_default_tabstop_size.htmlKatz
Y
6

In case anyone's using a StyledDocument (The link on the other answer died)

You create a TabSet which is an array of TabStops. In my case I only cared about the 1st tab, and I wanted it 20px from the left, so this code worked for me:

StyleContext sc = StyleContext.getDefaultStyleContext();
TabSet tabs = new TabSet(new TabStop[] { new TabStop(20) });
AttributeSet paraSet = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabs);
pane.setParagraphAttributes(paraSet, false);
Yaelyager answered 3/4, 2012 at 17:57 Comment(0)
L
-1

Took me a while to figure this out. And decided to use TabStop's in a TabSet that have calculated width based on the font size. This has to be reset when ever the font size changes (in the paint() method of the JEditPane).

Complicated stuff! :(

Langobardic answered 10/10, 2012 at 21:27 Comment(1)
This isn't an answer!Murillo

© 2022 - 2024 — McMap. All rights reserved.