public class User extends Frame implements ActionListener{
Label name=new Label("用户名:");//创建标签
Label paseword=new Label("密 码:");//创建标签
TextField nameTextField=new TextField(10);//单行文本域,输入用户名
TextField pasewordTextField=new TextField(10);//单行文本域,输入密码
Button submit=new Button("提交");//提交按钮
Button reset=new Button("重置");//重置按钮
User(){
pasewordTextField.setEchoChar('*');//密码加密
//三个面板,用于存放以上六个组件
Panel panel1=new Panel();
Panel panel2=new Panel();
Panel panel3=new Panel();
//将组件添加到相应的面板中
panel1.add(name);
panel1.add(nameTextField);
panel2.add(paseword);
panel2.add(pasewordTextField);
panel3.add(submit);
panel3.add(reset);
//对单行文本框和按钮添加事件监听器
nameTextField.addActionListener(this);
pasewordTextField.addActionListener(this);
submit.addActionListener(this);
reset.addActionListener(this);
//将面板添加到窗口中
add(panel1,"North");
add(panel2,"Center");
add(panel3,"South");
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof TextField){//判断触发事件的是不是TextField
Object object=e.getSource();
if(object==nameTextField){
pasewordTextField.requestFocus();}
if(object==pasewordTextField){
nameTextField.requestFocus();}
}
if(e.getSource() instanceof Button){//判断触发事件的是不是Button
if(e.getActionCommand().equals("提交")){
nameTextField.setText(null);
pasewordTextField.setText(null);}
if(e.getActionCommand().equals("重置")){
nameTextField.setText(null);
pasewordTextField.setText(null);}
}
}
public static void main(String[] args) {
final User user=new User();
user.setVisible(true);
user.setSize(250,200);
user.addWindowListener(new WindowAdapter(){//窗口关闭
public void windowClosing(WindowEvent e){
user.dispose();
}
});
}
}
按钮起作用了,你可以在按钮里面加System.out.print()输出有数据,应该是是你的nameTextField.setText(null);使用有误,我使用nameTextField.setText("任意字符"); 可以看到会改变
我看下下它的源码,当你设置的内容为null或者为空时,不会更新,即如果你传递的字符串为null或者"",不会更新,所以如果你要擦除,可以传递" "(注意中间有个空格)
,代码解释如下:
TextField.setText(String t)源码:
public void setText(String t) {
super.setText(t);
// This could change the preferred size of the Component.
invalidateIfValid();
}
它的父类TextComponent的setText(String t)代码如下:
/**
* Sets the text that is presented by this
* text component to be the specified text.
* @param t the new text;
* if this parameter is <code>null</code> then
* the text is set to the empty string ""
* @see java.awt.TextComponent#getText
*/
public synchronized void setText(String t) {
boolean skipTextEvent = (text == null || text.isEmpty())
&& (t == null || t.isEmpty());
text = (t != null) ? t : "";
TextComponentPeer peer = (TextComponentPeer)this.peer;
** // Please note that we do not want to post an event
**** // if TextArea.setText() or TextField.setText() replaces an empty text****
** // by an empty text, that is, if component's text remains unchanged.****
if (peer != null && !skipTextEvent) {
peer.setText(text);
}
}
注意我加粗的部分