Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line JTextArea

Tags:

java

text

swing

awt

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.

like image 370
David Avatar asked Oct 12 '11 19:10

David


People also ask

What is the difference between a JTextField and a JTextArea?

The main difference between JTextField and JTextArea in Java is that a JTextField allows entering a single line of text in a GUI application while the JTextArea allows entering multiple lines of text in a GUI application.

What is line wrap in JTextArea?

To wrap the lines of JTextArea we need to call the setLineWrap(boolean wrap) method and pass a true boolean value as the parameter. The setWrapStyleWord(boolean word) method wrap the lines at word boundaries when we set it to true .

What is JTextArea used for?

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.

Is JTextArea editable?

JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit the text .


1 Answers

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);
like image 170
camickr Avatar answered Sep 21 '22 10:09

camickr