Reputation: 356
I have a jTextField
and I want to check whether or not its values are empty.
So far, I can do it this way:
public static JTextField checkEmpty(JTextField jTextField) {
if (jTextField.getText().equals(" ") || jTextField.getText().isEmpty()) {
return null;
} else {
return jTextField;
}
}
However, I want to do it in the manner seen below:
JTextField jTextField = new JTextField();
jTextField.checkEmpty();
This would work by returning a jTextField
if it is not empty, and throw an exception or show showMessageDialog
otherwise.
I'm not sure if this is possible, so any help would be appreciated.
With all that said, the actual idea is I want to create a validation class for a swing component in my project. If I can make this work then I can put it in my validation class.
Thank you.
Upvotes: 0
Views: 66
Reputation: 1189
You need to implement your own class that extend the JTextField class and add method you want.
First: you should extend JTextField like:
class MyJTextField extends JTextField
{
public MyJTextField( String defVal, int size )
{
super( defVal, size );
}
public MyJTextField()
{
super( "", size );
}
}
Second: you should add your checkEmpty() method, and you don't need the JTextField argument:
public MyJTextField checkEmpty() {
if (this.getText().equals("") ||
this.getText().isEmpty())
{
// throw your exception.
// print message or whatever you need
return null;
} else {
return this;
}
}
Then: you can use it like this:
MyJTextField jTextField = new MyJTextField();
jTextField.checkEmpty();
Upvotes: 1