使用按钮清除 TextField (Java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24473427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:24:30  来源:igfitidea点击:

Clear TextField using Button (Java)

javatexttextboxswtclear

提问by user3466159

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

        }
    });

采纳答案by greg-449

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

回答by Niknea

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

正如亚历山大提到的,在你的类中实现动作监听器,然后简单地监听特定按钮是否被按下。如果是,请使用此代码清除文本字段。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)

请记住,您需要使用这行代码来触发您的动作侦听器事件,否则它将无法工作。 buttonName.addActionListener(this)

Have fun programming!

玩得开心编程!

回答by DroidRocks

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

    }
    });