62,628
社区成员
发帖
与我相关
我的任务
分享
/**
* The value of the text.
* A <code>null</code> value is the same as "".
*
* @serial
* @see #setText(String)
* @see #getText()
*/
String text;
这里,text 没赋值,就是 text =null;
看赋值语句,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);
}
}
我们看见,如果text 是null, t 是"", skipTextEvent 是true, peer.setText(text);不执行。
问题关键是,我们在文本框里输入内容了,text是否改变了?测试是没有改变还是null,也就是说只是给文本框里输入内容,底层的text并没改变. 所以就会出现楼主看到的情况。
如果要想达到清除的目的,可以先使用getText(), 读一下文本框内容,在getText()代码里,text被赋值了。
/**
* Returns the text that is presented by this text component.
* By default, this is an empty string.
*
* @return the value of this <code>TextComponent</code>
* @see java.awt.TextComponent#setText
*/
public synchronized String getText() {
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
text = peer.getText();//--------------------------------------看这句。
}
return text;
}
所以,楼主代码加一句,text1.getText(), 就会清除掉文本框内容了。
public void actionPerformed(ActionEvent e)
{ //String t="";
if (e.getSource()==button){ //获得当前事件源
text1.getText();
text1.setText(""); //清除文本框
}
}