3

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.

Soumasish
  • 53
  • 1
  • 9
  • 1
    Works for me as excepted. Type something click on reset and the field is empty. – pL4Gu33 Aug 18 '14 at 17:54
  • I see the problem as well. What version of Java are you using? I seem to remember seeing this as a known bug, let me see if I can find that... – Kevin Workman Aug 18 '14 at 18:06
  • I use both Java 7 update 65 and Java 8 update 11 and the problem seems to persist in both – Soumasish Aug 18 '14 at 18:11
  • Why use AWT components rather than Swing? See [this answer](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon AWT. – Andrew Thompson Aug 19 '14 at 13:18
  • @AndrewThompson , thanks for the link. I was supposed to use AWT only for creating a form application as my requirement and hence the components. – Soumasish Aug 19 '14 at 17:37

2 Answers2

7

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.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
-1

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

  • 2
    How is this different from the accepted answer posted 4 years ago? Especially "see if it works"? OP already confirmed it works. – Max Vollmer Oct 14 '18 at 05:46