Question

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();
    }
});
Was it helpful?

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.

OTHER TIPS

You can do this:

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

Just an addition to others' code.

public void textfieldMouseClicked(java.awt.event.MouseEvent evt) {                                      
    uname_tf.setText(null);
} //This will set the JTextfield blank on mouse click//      

public void textfieldFocusLost(java.awt.event.FocusEvent evt) {                                   
    uname_tf.setText("Username");
} //This will bring back the default text when not in focus//

Hope it helps, Cheers!!!

If you want it just one Click on it to delete the text you can do like this :

textField.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                textFieldMousePressed(evt);
            }
        });
 private void textFieldMousePressed(java.awt.event.MouseEvent evt) {
          textField.setText("");
    }

Add 1 line to you buttonMethod e.g:

txtfield.clear();

or set your txtfield to an empty string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top