JTextPane换行

问题描述 投票:1回答:2

询问者说,在this question

文本超出宽度时,JTextPane确实有自动换行功能

似乎并非如此。

scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

this.contentPane.add(scrollPane);

txtrFghj = new JTextPane();
txtrFghj.setBorder(null);
txtrFghj.setContentType("text/html");
txtrFghj.setText(content);

scrollPane.setViewportView(txtrFghj);

在给定的代码摘录中,content的内容根本不会包装,它只是超出了窗口的可见大小。如果窗口不够大,则无法完全看到长句。

如何实现换行?

我试过了

txtrFghj.setSize(50,50);

但这根本不会改变任何行为。

java swing line word-wrap jtextpane
2个回答
4
投票

您的代码中必须有其他内容阻止其正常工作。

这是一个小的演示示例,其代码相同,运行得很好:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

public class TestLineWrap {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestLineWrap().initUI();
            }
        });

    }

    protected void initUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextPane editorPane = new JTextPane();
        editorPane.setContentType("text/html");
        editorPane
                .setText("<html>Some long text that cannot hold on a single line if the screen is too small</html>");
        JScrollPane scrollPane = new JScrollPane(editorPane);
        scrollPane
        .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        frame.add(scrollPane);
        frame.setSize(200, 400);
        frame.setVisible(true);
    }
}

1
投票

感谢Guillaume,我想出来了,虽然我花了三个小时才意识到:断线非常确实在这里工作,但字符串断裂不起作用,可以在问题中引用的thread中看到。

我的JTextPane内容如下所示:

<html>
   <body>
    <br>
    <font color="red">bla bla bla bla</font>\r\n
    <u>someVeeeeeeeeeeeeeryLooooongString__WithOUTanySpacesInBetweeeeeeeeeeeeeeeeeeeeeeeeen</u>
    <b>more text</b>
    // ........ a lot of more HTML
    Some funny SENTENCE which is longer than JTextPane.getSize().width usually allows. This sentence was NOT LINE WRAPPED which made me ask the question.
   </body>
</html>

现在,如果VeeeeryLooongString没有扩展JTextPane的宽度,那么SENTENCE将被换行。一直以来,我都没有想到TextPane对象中的长字符串以及它如何影响整个换行行为。

删除这个千兆字符串为我解决了这个问题。

有关此主题的更多信息,请参阅此详细的question

现在我将尝试在JTextPanes中启用String换行,为此可以在引用的thread中再次找到更多信息。

编辑:字母包装可以完成,但似乎换行符<br>不再工作了。对于给定的问题,最简单的解决方法是不禁用水平滚动条并将其设置为AS_NEEDED

scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
© www.soinside.com 2019 - 2024. All rights reserved.