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
?
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.
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.
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).
JTextField(String text) : constructor that creates a new empty text field initialized with the given string.
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.
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