【问题标题】:Newlines in JEditorPaneJEdi​​torPane 中的换行符
【发布时间】:2012-02-29 17:08:20
【问题描述】:

我目前正在使用 JEditorPane 来显示从 Socket 读取的文本。我创建了 JEditorPane,获取它的 Document 并使用

添加文本
document.insertString(document.getEndPosition().getOffset(), string, null); 

这按预期工作,除了当它遇到 '\n'(用于换行符的字符)时,它似乎忽略它(即不打印任何内容),并且所有内容都出现在一行上。我四处寻找解决方案,但似乎找不到任何可行的方法(尝试用<br> 替换'\n',没有帮助,它只是打印出<br>

【问题讨论】:

    标签: java swing text newline jeditorpane


    【解决方案1】:

    它按您的预期工作。

    这里是代码。

    doc.insertString(doc.getEndPosition().getOffset(), "test\n", null);
    doc.insertString(doc.getEndPosition().getOffset(), "test\n", null);
    doc.insertString(doc.getEndPosition().getOffset(), "test\n", null);
    doc.insertString(doc.getEndPosition().getOffset(), "test\n", null);
    

    完整的代码。

        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();
    
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
        jScrollPane1.setViewportView(jEditorPane1);
    
        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    
        pack();
    
    1. 检查是否在编辑器窗格上设置了任何其他属性。
    2. 您使用的是什么编辑器工具包?
    3. 尝试打印输入并确保它带有'\n'

    你也可以使用,

        doc.insertString(doc.getLength(), "test\n", null);
    

    【讨论】:

    • 你是如何从套接字输入流中读取数据的?使用 BufferedReader.readLine()?如果是这种情况,读取的行将不包含 '\n';您需要手动添加它。
    • 捂脸!我在我的一种方法中手动添加了 '\n',而在另一种方法中忘记了它。这是第二个实际被调用的。糟糕!
    猜你喜欢
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 2011-06-06
    • 2011-03-07
    • 2011-08-20
    • 2020-09-08
    • 2013-10-06
    相关资源
    最近更新 更多