如何在JEditorPane中设置标签大小?
可以使用setTabSize(int)
轻松设置JTextArea
的选项卡大小。
使用JEditorPane
有类似的方法吗?
现在,我的窗格中带有标签的文字如下所示:
if (stuff){ more stuff; }
而且,我更喜欢一个更小的制表位:
if (stuff){ more stuff; }
由于JEditorPane旨在支持不同类型的内容类型,因此它不提供直接指定“选项卡大小”的方法,因为其含义应由内容模型定义。 但是,当您使用的是PlainDocument或其后代的模型时,会有一个“tabSizeAttribute”提供您要查找的内容。
例:
JEditorPane pane = new JEditorPane(...); ... Document doc = pane.getDocument(); if (doc instanceof PlainDocument) { doc.putProperty(PlainDocument.tabSizeAttribute, 8); } ...
来自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";
如果有人使用StyledDocument(另一个答案的链接死了)
您创建一个TabSet,它是TabStops的数组。 在我的情况下,我只关心第一个标签,我希望它从左边20px,所以这段代码对我有用:
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);
我花了一段时间才弄明白这一点。 并决定在TabSet中使用TabStop,它根据字体大小计算宽度。 必须在字体大小改变时重置(在JEditPane的paint()方法中)。
复杂的东西! 🙁