Clearing contents of TextField using setText does not work in AWT

不问归期 提交于 2019-12-18 08:57:15

问题


I am having problems clearing contents of TextField in AWT using setText() method. Apparently, setText("") does not clear the contents of the TextField on pressing the 'Reset' button. 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.


回答1:


I see the problem as well using 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. If somebody finds the filed bug there would be more information there.




回答2:


Add space in setText(" ") in function and see if it works. But there after there will be one space.



来源:https://stackoverflow.com/questions/25369221/clearing-contents-of-textfield-using-settext-does-not-work-in-awt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!