简体   繁体   English

使用setText清除TextField的内容在AWT中不起作用

[英]Clearing contents of TextField using setText does not work in AWT

I am having problems clearing contents of TextField in AWT using setText() method. 我在使用setText()方法清除AWT中TextField内容时遇到问题。 Apparently, setText("") does not clear the contents of the TextField on pressing the 'Reset' button. 显然,在按下“重置”按钮时, setText("")不会清除TextField的内容。 Here's my program: 这是我的程序:

import java.awt.*;
import java.awt.event.*;

public class form extends Frame
{

    Label lbl = new Label("Name:");
    TextField tf = new TextField();
    Button btn = new Button("Reset");

    public form()
    {
        tf.setColumns(20);

        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });


        btn.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
               tf.setText("");  //Problem occurs here. This does not clear the contents of the text field on pressing the 'Reset' button.

            }
        });


        add(lbl);
        add(tf);
        add(btn);

        setLayout(new FlowLayout());
        setSize(400,100);
        setVisible(true);
        setTitle("Form");

    }


    public static void main(String[] args) 
    {
        new form();
    }

}

Can someone please tell me where I went wrong or suggest an alternative? 有人可以告诉我哪里出了问题或建议替代方法吗? Thanks. 谢谢。

I see the problem as well using Java 8u11. 我也使用Java 8u11看到了问题。 I seem to remember this being filed as a known bug, but I can't seem to find it now. 我似乎还记得这是一个已知的错误,但是现在似乎找不到。

A solution that works for me is to add an intermediate step: 一个对我有用的解决方案是添加一个中间步骤:

public void actionPerformed(ActionEvent e) {
   tf.setText(" ");  
   tf.setText("");
}

I'm not sure why this is necessary, I think it's a bug with the setText() function specifically ignoring empty Strings. 我不确定为什么这样做是必要的,我认为这是setText()函数的一个错误,该函数专门忽略了空字符串。 If somebody finds the filed bug there would be more information there. 如果有人发现了已提交的错误,那里将会有更多信息。

Add space in setText(" ") in function and see if it works. 在函数的setText(“”)中添加空格,然后查看是否可行。 But there after there will be one space. 但是之后会有一个空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM