2013-04-09 78 views
2

我有這個代碼..在這裏,當我輸入數字「6」在文本字段中,文本應該顯示在textarea ..但之後,如果我輸入任何其他數字,我希望textarea內容清楚。但是當我執行我的代碼時,即使輸入不同的數字,textarea的舊內容仍然保留。請幫忙!重置文本區域內容

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); 
    } 
} 
+1

我在我的電腦上運行這個例子,如果我輸入除「6」之外的其他文本字段(如果我輸入「6」,它將textarea設置爲「文本」),TextArea會清除 – 2013-04-09 17:44:26

+0

您的意思是你想要TextField被清除? – 2013-04-09 17:45:32

+0

TextArea itseld ..它的工作..但它並不一直工作..特別是當有兩個文本區域..是否有我的軟件或什麼問題? – praveena 2013-04-09 18:00:02

回答

2

寫你的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(); 
    } 

的錯誤是,你沒有寫之後清除文本字段! 現在它通過在if條件下被清除

希望這可以解決您的問題!

+0

不,它不:(它仍然是「文本」本身..事情只是味精「無效味精」得到顯示,但文本字段不清除:( – praveena 2013-04-09 17:53:50

0

你應該paint(Graphics g)方法中調用super.paint(g):現在

public void paint(Graphics g) { 
    super.paint(g); 
    g.drawString(msg,350,250); 
    } 
0

text.setText("");不會做任何事情,它會一樣//text.setText("");

所以更好的做法是採取的ASCII碼的幫助,

對於空字符ASCII值爲0,在unicode中,我們可以將其寫爲'\u0000'

,最終這個聲明肯定會工作:text.setText(""+'\u0000');

注:自己沒方法是TextArea類以清除該地區... 所以,你必須要做到這一點你自己。