How to make text area text automatically go to the next line when line is finished?

akki0996 picture akki0996 · Mar 9, 2013 · Viewed 12.6k times · Source

This is my code for text field. It is not changing the line when the line ends, but continues to go on, making the frame look weird.

I tried to use a scroll pane, but it did not help me.

JTextArea TextArea = new JTextArea(7,10);
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
TextPanel.add(TextArea, gridConstraints);
TextArea.setEditable(true); 

Answer

Reimeus picture Reimeus · Mar 9, 2013

Without line & word wrapping, the size of a JTextArea will grow beyond its original size. You could call:

textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);

Side notes:

  • JTextArea are typically placed in JScollPane containers to facilitate scrolling.
  • Java naming conventions indicate that variables start with a lowercase letter, making TextArea textArea