Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

java - Clearing contents of TextField using setText does not work in AWT

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...