我在使用 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 时也看到了这个问题。我似乎记得这是作为已知错误提交的,但我现在似乎找不到了。
对我有用的解决方案是添加一个中间步骤:
public void actionPerformed(ActionEvent e) {
tf.setText(" ");
tf.setText("");
}
我不确定为什么这是必要的,我认为这是 setText() 函数专门忽略空字符串的错误。如果有人发现了提交的错误,那里会有更多信息。
关于java - 使用 setText 清除 TextField 的内容在 AWT 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25369221/