Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 496
Michal Vician Avatar asked Jun 13 '12 15:06

Michal Vician


People also ask

What is the default found for JTextArea?

Constructs a new TextArea. A default model is set, the initial string is null, and rows/columns are set to 0.

What is the use of JTextArea component?

The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field.

What is JTextArea?

A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with the java. awt. TextArea class where it can reasonably do so.


1 Answers

Use the JTextArea#setColumns method to adjust the width

like image 188
Robin Avatar answered Oct 07 '22 14:10

Robin