GUI Refinements – Focus

  1. Zeller Pascal
  2. Zeller Java
  3. validDate Revisited – Python
  4. validDate Revisited – Java
  5. Java GUI
  6. GUI – Refinements – ComboBoxes
  7. GUI – Refinements – Error Messages
  8. GUI Refinements – Focus
  9. GUI Refinements – Today

The next refinement, is that I want the Year textfield to clear when it is either clicked on or tabbed to. In order to do this i need to implement not only the ActionListener but also the FocusListener. To do this I simply have to change the class header from:

public class GUI extends JFrame implements ActionListener

to this:

public class GUI extends JFrame implements ActionListener, FocusListener

I then have to write two methods, focusGained and focusLost. The focusGained method will have the code clearing the default text and the focusLost method will check for an empty string, if it finds an empty string it will reset the textfield back to the default value (“0000”). The code is as follows:

public void focusGained(FocusEvent e) {
        textFieldYear.setText(null);
    }

    public void focusLost(FocusEvent e) {
        if (textFieldYear.getText().equals("")){
            textFieldYear.setText("0000");
        }
    }

The last this is to add a single line of code to the GUI method to use these methods, it is simply:

textFieldYear.addFocusListener(this);

This was one of the easier refinements to implement.