Search code examples
javaswingjtextarea

How to set the maximum necessary size of a JTextArea


I have a non-editable JTextArea. I want the size of this JTextArea to be no larger than needed to contain the text it has. However, if I expand the component containing it, the JTextArea will expand as well, leaving annoying empty space. I am not putting it in a JScrollPane (I cannot use a JScrollPane in this instance). The container that has the JTextArea is using BoxLayout.

So, basically, I have this:

_____________________________
|adfadfvfvanalfvnavlavnaklvf|
|afdviadanklfvnaflanvlakdnfv|
|efvavsavasv                |
|                           |
|___________________________|

And I want this:

_____________________________
|adfadfvfvanalfvnavlavnaklvf|
|afdviadanklfvnaflanvlakdnfv|
|efvavsavasv________________|

RELEVENT CODE:

private void initializeAllComponents(){
    this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

    this.setHeader();
    this.add(header);

    this.setDescription();//This is the JTextArea
    this.add(desc);

    this.setBody();
    this.add(body);

    this.setFooters();
}

private void setDescription(){
    desc = new JTextArea(skill.getDesc());
    desc.setFont(new Font("URW Chancery L", Font.ITALIC, 16));
    desc.setBackground(new Color(218, 217, 199));
    desc.setEditable(false);
    desc.setLineWrap(true);
    desc.setWrapStyleWord(true);
}

Solution

  • You can just put the JTextArea in the north part of a BorderLayout, e.g.

    contentPane.setLayout(new BorderLayout());
    contentPane.add(textArea, BorderLayout.NORTH);
    

    It will then use only as much space as necessary.

    Note: If you need line wrapping don't forget textArea.setLineWrap(true);.