Maythe
Maythe

Reputation: 586

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

Upvotes: 1

Views: 2341

Answers (3)

Adir Dayan
Adir Dayan

Reputation: 1617

I've used JTextArea instead of JTextPane

then used method:

textArea.setLineWrap(true);

Upvotes: 0

E. v. Kitzing
E. v. Kitzing

Reputation: 1

At least in my case, the following coding works. If you add the JTextPane into a JPane with border layout and add that pane into the JScrollPane, then the lines would not wrap.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347184

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

    }
}

Upvotes: 2

Related Questions