Search code examples
javaswingword-wrapjtextpane

JTextPane won't wrap


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

Solution

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

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

    Updated with additional example

    Try this instead. This worked for me.

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