Search code examples
javaswingjtextareaword-wrap

JTextArea with adaptative width issue


I'd like to have a JTextArea which behaves this way:

  1. Always show a vertical scroll bar

  2. When text reaches the end of the line, it continues on next line (instead of continuing on the same line but being hidden)

  3. When the window is resized, the text is refreshed, so if for example the window is larger, the height of the text gets lower.

Point 1. is easy, but I can't find a way for points 2. and 3, so any help will be appreciated. Here is the sample code I wrote:

public class TestCode2 {

  public static void main(String[] args) {

    JFrame window = new JFrame("Test2");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setSize(400, 200);

    JPanel container = new JPanel(new BorderLayout());
    window.add(container);

    JLabel labelNorth = new JLabel("North");
    container.add(labelNorth, BorderLayout.NORTH);

    JLabel labelSouth = new JLabel("South");
    container.add(labelSouth, BorderLayout.SOUTH);

    JTextArea ta = new JTextArea();
    JScrollPane taScrollPane = new JScrollPane(ta);
    taScrollPane
        .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    taScrollPane
        .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    container.add(taScrollPane);

    window.setVisible(true);
  }
}

Solution

  • This:

    jtextarea.setLineWrap(true);
    jtextarea.setWrapStyleWord(true);
    

    will make the textarea continue on the next line when reaching the end of the current one. Basically, jtextarea.setLineWrap(true) tells the textarea to continue to the next line breaking words, i.e. you would get something like this:

     _________
    |I'm so co|
    |ol       |
    |_________|
    

    Then, jtextarea.setWrapStyleWord(true) tells the textarea to enable word wrapping, so the result will be this:

     _________
    |I'm so   |
    |cool     |
    |_________|
    

    To resize the JTextArea when the frame resizes, use a ComponentListener;

    jframe.addComponentListener(new ComponentAdapter(){
        public void componentResized(ComponentEvent e) {
            //the frame was resized, resize the textarea here
        }
    });
    

    UPDATE

    As mKorbel says, To resize the JTextArea, use a LayoutManager and let it do all the work