I have a textfield in a class called RegPanel. I have instantiated my gui. I now need to find out if the field is empty when focus is lost, and if it is, I need to bring focus back to the textfield with a message “Please enter a name.”
So far I have tried `
public void focusLost(FocusEvent e)
{
if(e.getSource()==gui.regPanel.regTextField.getText().trim().equals(""))
{
gui.regPanel.regTextField.setText("Please enter a name");
gui.regPanel.regTextField.requestFocus();
}
else gui.regPanel.regTextField.setText("");`
as well as I have tried variations on
if(e.getSource()==gui.regPanel.regTextField.getText().length()=0)
These are returning compile errors like ‘expected value found int, and ‘incomparable types:java.lang.Object and boolean.
I think I need to cast it to a string, but can’t figure out how.
In your if-statement you mixed up two comparisons in one. You want to test
Therefore you have to make two checks and combine them with and:
Remark: Your focus listener actually removes any text from your textfield if there is any (via the
setText("")).