Search code examples
javaswinglayoutlayout-managerjtextarea

Fix Height of JTextArea


I'm still inexperienced with creating Java GUIs, and I'm having trouble with the JTextArea. I would like to fix it's height (number of columns) but it seems to always fill the available space. I've read on the Internet that you should place it inside a JScrollPane, which I've done, but the same thing happens.

This is some example code:

public class TestWindow extends JFrame {

    public TestWindow() {
        super();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);

        add(new JScrollPane(new JTextArea(5, 10)));

        setVisible(true);
    }

}

With this code, the JTextArea fills the whole window. Any way I can fix it to a specific number of rows and columns? Could it have something to do with the layout manager?


Solution

  • Yes, the default layout is BorderLayout which expands all the content to fit the whole area, you have to set a new Layout, I recommend GridBagLayout to extensive control of the sizes, or which I most use, BoxLayout