Clear Textfield Using Button (Java)

I'm trying to clear two text boxes using the following code. It executes without error but the numbers entered in the text box do not change once the button is clicked. Any suggestions? Thanks in advance! :)

btnClear = new Button(shlTestProject, SWT.NONE);
btnClear.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        textBox1.setText("");
        textBox2.setText("");
    }
});
btnClear.setBounds(240, 298, 75, 25);
btnClear.setText("Clear");



    textBox1= new Text(shlTestProject, SWT.BORDER);
    textBox1.setBounds(224, 386, 76, 21);
    textBox1.addVerifyListener(new VerifyListener() {
        public void verifyText(VerifyEvent e) {
            e.doit = false; //assume we don't allow it
            char myChar = e.character; // get the character typed
           if (Character.isDigit(myChar)) e.doit = true; // allow 0-9 
          if (myChar == '\b') { //allow backspace
          e.doit = true;
          }

        }
    });

3 Answers

Use a Selection Listener to deal with with the button being pressed:

btnClear.addSelectionListener(new SelectionAdapter()
  {
    @Override
    public void widgetSelected(SelectionEvent e)
    {
      textBox1.setText("");
      textBox2.setText("");
     }
  });
4
 clear.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick (View v){
        textView.setText("");

    }
    });

As Alexander mentioned, implement Action Listener into your class, then simply listen if the specific button was pressed. If it was, use this code to clear the text field. TextFieldName.setText("");.

Remember, you need to trigger your action listener event by using this line of code, else it won't work. buttonName.addActionListener(this)

Have fun programming!

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest