Jesus Zavarce Jesus Zavarce - 1 month ago 7
Java Question

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
?

Answer

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.

Comments