2013-01-21 115 views
1

我正在嘗試清除寫有文字的文本區域。 我一直在嘗試使用repaint()方法,因爲我認爲這種重置文本區域,但它一直沒有工作。清除JTextArea不能正常工作

我正在使用文本區域以及列表。點擊列表中的成員後,所述成員將顯示在文本區域中。所以當他們被「取消選擇」時,我需要以前寫的成員從文本區域消失。

下面是的valueChanged,這是在事情發生代碼:

public void valueChanged(ListSelectionEvent e) 
{ 
     Object source = e.getSource(); 
     int[] indices = songList.getSelectedIndices(); 
     DecimalFormat df = new DecimalFormat("#0.00"); 

     Song[] selection = new Song[indices.length]; 
     for(int i = 0; i < indices.length; i++) 
     { 
      selection[i] = songCollection[indices[i]]; 
     } 
     if(e.getValueIsAdjusting() == false) 
     { 
      for(int i = 0; i < selection.length; i++) 
      { 
       textArea.repaint(); //Shouldn't this work? 
       textArea.append(selection[i].getTitle() + " " + selection[i].getArtist() + " " + df.format(selection[i].getPrice()) + "\n"); 

      } 

     }    

} 

PS,我是很新,堆棧溢出,所以如果我做錯了什麼,請隨時告訴我。

+1

RTFM..'repaint'不清除組件。有關更多信息,請參閱[如何使用文本區域](http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html)。 – mre

+2

'repaint()'不會更改'JTextArea'的'Document'中的文本,它只是重繪組件。您正在尋找'textArea.setText(「」);' – Reimeus

回答

4

JTextComponent#setText

設置此TextComponent到指定文本。如果文字 爲null或爲空,則具有簡單刪除舊文字的效果。當插入 文本時,由此產生的脫字符位置由 確定脫字符類的實現。

因此,要明確從JTextArea成分的文字,無論是做setText(null),或setText("")

2

如上所述。

setText(「」)也適用於文本字段btw。