1

我正在尝试让 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);
    }
}
4

3 回答 3

2

根据您的布局,JTextPane可能会或可能不会包装,这取决于它对可用尺寸的感知。

相反,添加JTextPaneJScrollPane...

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));
        }

    }
}
于 2013-01-31T22:36:46.103 回答
0

至少在我的情况下,以下编码有效。如果将 JTextPane 添加到具有边框布局的 JPane 中并将该窗格添加到 JScrollPane 中,则这些行将不会换行。

于 2020-01-29T16:36:52.533 回答
0

我用过JTextArea而不是JTextPane

然后使用方法:

textArea.setLineWrap(true);
于 2021-03-16T20:58:53.053 回答