Michal Vician
Michal Vician

Reputation: 2545

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

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;
    }

}

Upvotes: 7

Views: 15152

Answers (3)

Ahmad Moussa
Ahmad Moussa

Reputation: 1324

set linewrap to true => textArea.setLineWrap(true); this will make the maximum line width = textarea with

Upvotes: 2

user3015208
user3015208

Reputation: 11

Change this line of code textArea.setPreferredSize(newPrefSize); to textArea.setSize(newPrefSize); The height will be dynamically adjusted.

Upvotes: 0

Robin
Robin

Reputation: 36601

Use the JTextArea#setColumns method to adjust the width

Upvotes: 5

Related Questions