我想设置制表符 \t 的大小JTextPane
宽度为 4 个空格。
经过一番谷歌搜索后,我发现了一些东西,我将在这里包含我所尝试过的东西以及它们失败的原因。
如何在 JEditorPane 中设置选项卡大小?
JTextPane
不是一个普通的文档。
Java JTextpane 选项卡大小
Eclipse 引发了一些错误:
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
本页讨论样式JTextPane
。我从中改编的代码如下:
MutableAttributeSet set = new SimpleAttributeSet(pane.getParagraphAttributes());
StyleConstants.setLeftIndent(set, 40);
StyleConstants.setRightIndent(set, 40);
我想将 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 的默认字体时,空格的宽度不是很宽,因此实际的选项卡不会那么大。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)