How do I make a JTextPane
multiline?
That is, I want to achieve the same effect as if it was a JTextArea
with wrapStyleWord
set to true
However, JTextPane
doesn’t have such a property (not directly, at least)
import javax.swing.*;
// no wrapping yet
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
JPanel myPanel = new JPanel();
JTextPane myTextPane = new JTextPane();
myTextPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
myPanel.add(myTextPane);
frame.add(myPanel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
Here’s what I tried. It wouldn’t necessarily achieve what I want (as I want the cursor to jump to the next line, stretching the “text area” with no scrollbars), but it would bring me closer to the desired result. Anyway, even with this code, the text still goes beyond the visible “text area” without wrapping to the next line
myTextPane.setPreferredSize(new Dimension(100, 50));
JScrollPane myScrollableTextPane = new JScrollPane(myTextPane);
myScrollableTextPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
myScrollableTextPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
myPanel.add(myScrollableTextPane);