java - JTextPane 不会换行

标签 java swing word-wrap jtextpane

我正在尝试让 JTextPane 自动换行。我已经搜索过这个站点和整个 Internet,似乎 JTextPane 应该默认自动换行 - 人们遇到的大多数麻烦是禁用换行或让换行在 JScrollPane 中工作。我尝试了 TextPanes、ScrollPanes 和 JPanel 的各种组合,但都无济于事。下面是经过测试但仍然存在问题的最简单的可能代码(没有换行)。

public class Looseleaf extends JFrame{

    public Looseleaf(){
        this.setSize(200,200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        JTextPane txtPane = new JTextPane();
        this.add(txtPane);
        this.setVisible(true);
    }
}

最佳答案

根据您的布局,JTextPane 可能会或可能不会被包裹,这取决于它感知到的可用大小。

相反,将 JTextPane 添加到 JScrollPane 中......

public class Looseleaf extends JFrame{
    public Looseleaf(){
        this.setSize(200,200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        JTextPane txtPane = new JTextPane();
        this.add(new JScrollPane(txtPane)); // <-- Add the text pane to a scroll pane....
        this.setVisible(true);
    }
}

更新了额外的例子

试试这个。这对我有用。

public class TestTextPaneWrap {

    public static void main(String[] args) {
        new TestTextPaneWrap();
    }

    public TestTextPaneWrap() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            JTextPane editor = new JTextPane();
            editor.setMinimumSize(new Dimension(0, 0));
            add(new JScrollPane(editor));
        }

    }
}

关于java - JTextPane 不会换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14636186/

相关文章:

java - Spring - 设计实用模块

java - 我可以调用一个方法并从 p :commandLink 一起重定向到另一个页面吗

java - 是否需要在每次查询时关闭实体管理器?

java - 如何在文本文件中填充方法的输出

python - 有没有办法让 vim 以 79 个字符自动包装 python 字符串?

java - 删除 JTable 中的所有行

java - 调度程序可以挂起一个线程并执行另一个线程/工作吗?

java - 如何在按钮点击之间创建延迟(以防止按钮垃圾邮件)

flutter - 如何包装 RadioButtonGroup 的标签?我在哪里可以提供 Expanded 或 Flexible?

iPhone:UITextView 环绕 UIImage?