Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing: the initial String of JTextField is an empty String

About the constructor of JTextField, the javadoc says:

public JTextField()

Constructs a new TextField. A default model is created, the initial string is null, and the number of columns is set to 0.

But when I use this constructor, the method getText() of JTextField returns an empty String, for example:

boolean b = new JTextField().getText().isEmpty();  // returns true.

Why the value returned by getText() is an empty String instead of null?

like image 853
Jesus Zavarce Avatar asked Aug 29 '16 11:08

Jesus Zavarce


People also ask

How do I know if JTextField is empty?

So Java allows us to check if a text field is empty or not through the isEmpty() function. You can then do anything after this including prompt the user to enter in something or whatever.

What is JTextField in Java Swing?

JTextField is a lightweight component that allows the editing of a single line of text. For information on and examples of using text fields, see How to Use Text Fields in The Java Tutorial. JTextField is intended to be source-compatible with java. awt. TextField where it is reasonable to do so.

What is the default value of JTextField?

If the initial text is not specified, its default value is null (the text field is empty). If the number of columns is not specified, its default value is 0 (then the text field's width is calculated based on the initial text).

Is JTextField a string?

JTextField(String text) : constructor that creates a new empty text field initialized with the given string.


1 Answers

JTextField get the text from the Document , default implementation PlainDocument never returns null. even though you tried to call JTextField.setText(null), it will just clear the value of the Document content, but still getText will return empty string.

like image 119
hunter Avatar answered Sep 28 '22 12:09

hunter