本文介绍了JTextPane不会包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JTextPane换行.我已经在这个站点和整个Internet上进行了搜索,似乎JTextPane默认情况下应该自动换行-人们最麻烦的是禁用自动换行或使自动换行在JScrollPane中工作.我尝试了TextPanes,ScrollPanes和JPanels的各种组合,但都无济于事.下面是经过测试的最简单的可能仍然有问题的代码(无包装).

I'm trying to get JTextPane to word-wrap. I've searched this site and across the Internet and it seems that JTextPane is supposed to word-wrap by default- most trouble people have is with disabling the wrap or getting the wrap to work inside a JScrollPane. I've tried various combinations of TextPanes, ScrollPanes and JPanels, to no avail. Below is the simplest possible code tested that still has the problem (no wrap).

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可能会包裹也可能不会包裹,这取决于它的可用大小.

Depending on you layout, JTextPane may or may not wrapped, based on what it perceves as it's available size.

相反,改为将JTextPane添加到JScrollPane ...

Instead, add the JTextPane to a JScrollPane instead...

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

    }
}

这篇关于JTextPane不会包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 09:56