我正在使用JTexPane
来显示一些包含需要突出显示的部分的文字。如何正确填充空格?
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class test2 {
public static void main(String[] args) {
final JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
textPane.setText("<html>" + text.replaceAll("\\n", "<br/>").replaceAll(" ", " ").replaceAll("\\t", " ") + "</html>");
StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, Color.blue);
doc.setCharacterAttributes(0, text.length(), sas, false);
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Test");
frame.setPreferredSize(new Dimension(900, 800));
frame.getContentPane().add(textPane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
static String text = "\n" +
"\n" +
" pop12 2014-01-12 just a padded text\n" +
" line 2\n" +
" line 3 \n";
}
这显示以下内容:
答案 0 :(得分:2)
您可以尝试定义默认的标签停止尺寸,例如http://java-sl.com/tip_default_tabstop_size.html
或者您可以通过setParagrahAttributes()
为段落添加自定义TabSet(制表符数组)答案 1 :(得分:0)
设置自定义TabSet的示例:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextPaneTabs
{
public static void setTabs( JTextPane textPane, int charactersPerTab)
{
FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
int charWidth = fm.charWidth( 'w' );
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, 8 );
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();
}
});
}
}