Setting fixed width of JTextArea while height should be automatically adjusted to its content

Michal Vician picture Michal Vician · Jun 13, 2012 · Viewed 12.8k times · Source

When I run the sample code below the width of JTextArea is fixed (100px) while its height is dynamically adjusted as I type some text in it.

So for example I start with this:

--------------------
| some text        |
--------------------

and as I type more text the height of JTextArea expands so it fits the content while preserving the width:

--------------------
| some text, some  |
| other longer text|
| etc...           |
--------------------

How can I double the width of JTextArea? When I do it by changing preferredSize the height is not dynamic anymore.

public class TestTextArea extends JFrame {

    public static void main(String[] args) {
        new TestTextArea().setVisible(true);
    }

    public TestTextArea() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0,0,800,600);
        setContentPane(createPane());
    }

    protected Container createPane() {
        JTextArea textArea = createTextArea();

        // ------------------------------------------
        // UNCOMMENT TO DOUBLE THE WIDTH OF JTextArea

//        Dimension oldPrefSize = textArea.getPreferredSize();
//        Dimension newPrefSize = new Dimension(oldPrefSize.width * 2, oldPrefSize.height);
//        textArea.setPreferredSize(newPrefSize);

        JPanel pane = new JPanel(new FlowLayout());
        pane.add(textArea);
        return pane;
    }

    protected JTextArea createTextArea() {
        JTextArea textArea = new JTextArea();
        textArea.setWrapStyleWord(true);
        textArea.setLineWrap(true);
        return textArea;
    }

}

Answer

Robin picture Robin · Jun 13, 2012

Use the JTextArea#setColumns method to adjust the width