user3466159
user3466159

Reputation: 27

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;
          }

        }
    });

Upvotes: 0

Views: 104259

Answers (3)

MD Tayobur Rahman
MD Tayobur Rahman

Reputation: 96

 clear.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick (View v){
        textView.setText("");

    }
    });

Upvotes: 1

greg-449
greg-449

Reputation: 111217

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("");
     }
  });

Upvotes: 4

Niknea
Niknea

Reputation: 39

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!

Upvotes: -3

Related Questions