0

How can I get the JTextPane to create a new line when the user types in something and it reaches the end of the screen/frame? Here is what I have:

JFrame frame = new JFrame("Frame");

JTextPane pane= new JTextPane ();
JPanel panel = new JPanel(new BorderLayout());
panel.add(pane);
JScrollPane scrollBar = new JScrollPane(panel);
        scrollBar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

frame.add(scrollBar, BorderLayout.CENTER);

Please note this is NOT for some fixed string in the JTextPane, meaning that the pane is blank by default and the text is added by user input. When the user is typing something and the word has reached the end of the screen, the text should continue on a new line, rather than continuing on the same line...

swag antiswag
  • 349
  • 1
  • 4
  • 12
  • 1
    You can use a `JTextArea` and call `setWrapStyleWord(true);` – Ian2thedv Dec 02 '15 at 08:27
  • I have to use a JTextPane – swag antiswag Dec 02 '15 at 08:32
  • If I recall, you can add the `JTextPane` to a `JPanel` using a `BorderLayout` and the add the `JPanel` to a `JScrollPane` – MadProgrammer Dec 02 '15 at 08:48
  • 1
    Look at this solution: [how-to-make-jtextpane-line-break](http://stackoverflow.com/questions/23883475/how-to-make-jtextpane-line-break) – JoGe Dec 02 '15 at 08:48
  • @MadProgrammer thanks for the reply, I'm not sure if I understand where to add the JTextPane. Do I add it to the JPanel or the BorderLayout? I have updated my code above – swag antiswag Dec 03 '15 at 07:50
  • `JScrollPane` -> `JPanel(BorderLayout)` -> `JTextPane` - don't know if will work, but I think I recall seeing it somewhere – MadProgrammer Dec 03 '15 at 08:02
  • @JoelGeiser, thanks I took a look that one of the links and that worked. Although, it works, I do not like the fact that I pretty much have to copy and paste that persons code to make it work, even though I am giving credit and reference to the source... – swag antiswag Dec 03 '15 at 08:40
  • Don't worry. You can use the code as you wish, Copy, use, change etc. – StanislavL Dec 03 '15 at 15:42

1 Answers1

0

I don't get why people keep asking this question. JTextPane normally wraps words :

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame mainFrame = new JFrame("test");
            mainFrame.setSize(100, 100);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            Container pane = mainFrame.getContentPane();
            JTextPane jtp = new JTextPane();
            JScrollPane scroll = new JScrollPane(jtp);
            pane.add(scroll);

            mainFrame.setVisible(true);
        }
    });
}
Sharcoux
  • 5,546
  • 7
  • 45
  • 78