开发者

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|
|afdviadanklfvnaf开发者_StackOverflowlanvlakdnfv|
|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);
}


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);.


I would use

desc.setMaximumSize(getPreferredSize());

to minimize the size of desc, since the preferred size of a JTextArea is defined by the number of rows and columns.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜