David
David

Reputation: 16028

Single line JTextArea

When you type into a JTextArea, it automatically adjust it's size to fit the text typed in.

A JTextField, however, does not seem to do that. Here's an SSCCE which demonstrates the problem:

public static void main(String[] args) {

    JFrame frame = new JFrame();
    frame.setLayout(new FlowLayout(FlowLayout.LEFT));
    frame.add(new JTextArea("I resize as you type."));
    frame.add(new JTextField("I don't."));
    frame.setSize(200,100);
    frame.setVisible(true);
}

Automatic resizing

I was wondering if there was a way readily available to make a JTextField adjust it's width. I wish I can just use a JTextArea, but I can only accept one line of input.

Upvotes: 6

Views: 6810

Answers (1)

camickr
camickr

Reputation: 324098

but I can only accept one line of input

Single Line Text Area shows how you can do this. The relevant code is

textArea.getDocument().putProperty("filterNewlines", Boolean.TRUE);

Upvotes: 10

Related Questions