Search code examples
javaswingjpaneljscrollpanejtextarea

Scrollable JTextArea that adjusts its size on resize


I've a JFrame with multiple panels. One of those should contain a JTextArea of a given size, that can scroll if the text exceeds the area, and that resizes acording to the frame size.

The thing is that when the panel is an instance of JPanel, it looks as I'd like to both in window or fullscreen size, as long as the content doesn't exceed the current area, when it does, it takes the space given to the other components, making them shrink in the frame (here it should show scrollbars instead).

On the other hand, when I use a JScrollPane, I can't manage to make it have the same behaviour of the JPanel, keeping the proper size. Actually it seem to adjust to it's content, and since it's empty, it's just some pixels wide.

How can I achieve what I'm looking for? Thanks in advance

Following the code that keeps the right size (JPanel):

        add(new JPanel(){
            {
                input = new JTextArea(20,20);
                input.setLineWrap(true);
                input.setBackground(Color.WHITE);
                input.setBorder(cb);

                this.setLayout(new BorderLayout());
                //this.setPreferredSize(new Dimension(20,20));
                this.setBorder(eb);
                this.add(input);
            }
        });

Solution

  • Don't add the text area to the frame.

    this.add(input); 
    

    Instead you need to add a JScrollPane containing the text area to the frame:

    this.add(new JScrollPane(input));