我有此代码..在这里,当我在文本字段中输入数字“ 6”时,应在文本区域中显示文本。但是,当我执行代码时,即使我输入其他数字,文本区域的旧内容也会保留。请帮忙!
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="front" width=500 height=500></applet> */
public class front extends Applet implements ActionListener {
String msg="";
TextArea text,text1;
TextField txt;
Button load, enter;
public void init() {
enter=new Button("Enter");
load=new Button("Load");
txt=new TextField(5);
text=new TextArea(10,15);
add(load);
add(text);
add(txt);
add(enter);
load.addActionListener(this);
txt.addActionListener(this);
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Load")) {
msg = "You pressed Load";
} else {
if(txt.getText().toString().equals ("6")) {
msg="Set the text for 6";
text.setText("Text");
} else {
msg="Invalid number";
text.setText("");
}
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg,350,250);
}
}
最佳答案
如下编写您的actionPerformed()方法
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Load")) {
msg = "You pressed Load";
} else {
if(txt.getText().toString().equals ("6"))
{
**text.setText("");**
msg="Set the text for 6";
text.setText("Text");
}
else {
msg="Invalid number";
text.setText("");
}
}
repaint();
}
错误是您没有在写入后清除文本字段!
现在通过在
text.setText("");
条件下使用if
将其清除希望这能解决您的问题!