在JTextPane上设置Java缩进大小

3
我想在 JTextPane 中设置制表符(\t)的大小为 4 个空格宽度。
经过一番搜索,我找到了一些尝试过的方法以及它们可能失败的原因。 如何在 JEditorPane 中设置制表符大小? JTextPane 不是一个普通文档。 Java JTextpane 制表符大小 Eclipse 弹出了一些错误信息:
Type mismatch: cannot convert from javax.swing.text.AttributeSet to 
 javax.print.attribute.AttributeSet

并且

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

这个页面讨论了如何使用JTextPane进行样式设置。我从这里适用的代码,制作了下面的内容:

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

MutableAttributeSet set = new SimpleAttributeSet(pane.getParagraphAttributes());
StyleConstants.setLeftIndent(set, 40);
StyleConstants.setRightIndent(set, 40);

1
我想将JTextPane中的缩进大小设置为4。4是什么?像素、字符还是...浔? - Andrew Thompson
1
我不清楚你所说的“缩进”是什么意思。这只是指文本窗格边缘和实际文本之间的空间吗?如果是这样,只需将其边框设置为正确大小的EmptyBorder即可。 - FredK
我不明白你所说的“缩进大小”是什么意思。通常缩进是指距离左边缘的空间,而你并没有解释为什么setLeftIndent(...)方法不起作用。我认为这应该是你应该使用的解决方案。但是你还谈到了制表符,这是基于文本窗格的数据而不是一行文本的起始缩进。 - camickr
1
你确定你没有导入错误的类吗?你应该使用 "import javax.swing.text.AttributeSet" 而不是 "import javax.print.attribute.AttributeSet"。 - Sharcoux
@Sharcoux 我刚刚检查了一下,我导入了正确的类,import javax.swing.text.SimpleAttributeSet; - Moon Cheesez
显示剩余2条评论
2个回答

3
我想将JTextPane中制表符\t的大小设置为4个空格宽度。
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();
            }
        });
    }
}

当然,如果使用JTextPane的默认字体,空格的宽度并不是很大,所以实际制表符也不会很大。

实际上正常选项卡的大小太大了。它大约有10个空格的宽度。 - Moon Cheesez
如果宽度相当大,则5个制表位不足。这还取决于字体。 - StanislavL
1
5个TabStops不够用。是的,将数组大小更改为更合理的值很容易。 - camickr

2
从链接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);
        }

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接