使用setText清除TextField的内容在AWT中不起作用
我在使用setText()
方法清除AWT中的TextField
内容时遇到问题。 显然, setText("")
在按下“重置”按钮时不会清除TextField
的内容。 这是我的计划:
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(); } }
有人可以告诉我哪里出错或建议替代方案吗? 谢谢。
我也看到了使用Java 8u11的问题。 我似乎记得这是一个已知的bug,但我现在似乎无法找到它。
对我有用的解决方案是添加一个中间步骤:
public void actionPerformed(ActionEvent e) { tf.setText(" "); tf.setText(""); }
我不确定为什么这是必要的,我认为这是setText()函数的一个错误,特别是忽略空字符串。 如果有人发现提交的错误,那里会有更多的信息。