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);
}
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.
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.
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 .
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.
JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit the text .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With