Search code examples
javaswingactionlistenerjtextfieldfocuslistener

How to delete text when a user clicks a JTextField?


In my program, the user writes something in a JTextField then clicks a 'generate' button, which triggers the characters in the JTextField to be drawn to a JPanel.

I would then like to clear all the text in the JTextField when the user clicks the JTextField again. I tried to achieve this by adding a FocusListener and an ActionListener to the JTextField, however my attempts did not work. Moreover, my implementation of the FocusListener gave an Unreachable Statement compiler error.

Is this possible to do in Java and if so how can I do this?

The code below is my ActionListener implementation.

dfaText = new JTextField(6);
dfaText.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        generateLabel.setText("NOOOOO!!!");
        dfaText.setText("");

        isDfaDrawn = false;
        canDraw = false;
        repaint();
    }
});

Solution

  • Add a mouse listener:

    field.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        field.setText("");
      }
    });
    

    Bear in mind this could get frustrating if the user legitimately clicks elsewhere and returns to the field. You may wish to maintain some state, e.g. only clear the field if the button has been clicked in the interim.