java - 如何在 JTextPane 中正确填充文本?

标签 java swing jtextpane

我正在使用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(" ", "&nbsp;").replaceAll("\\t", "&nbsp;&nbsp;") + "</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";

}

这显示以下内容:

enter image description here

最佳答案

您可以尝试定义默认制表位大小,如此处所述 http://java-sl.com/tip_default_tabstop_size.html

或者您可以通过 setParagrahAttributes() 为段落添加自定义 TabSet(选项卡数组)

关于java - 如何在 JTextPane 中正确填充文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22353733/

相关文章:

java - 单元测试 Java switch - 案例逻辑 - 多个单独的函数或多次调用

java - 如何在拖放过程中接收关键事件?

java - 如何通过网络加载文件并将其作为字符串处理

java - 拿起_JAVA_OPTIONS : -Xmx256M

java - 为 O/RM 系统(Hibernate)实现长期历史模式的最佳实践?

java - 从左边框滑动以打开 Activity

java - 尝试将 2 (JLabel, JSlider) 添加到具有 BorderLayout 的面板,仅绘制 JSlider

java - 具有多个 JFrame 窗口的 EDT 位置

java - JTextPane:setCharacterAttributes 的渲染器是什么?

java - 当 Pane 宽度超过指定值时,在 JTextPane 中换行文本