2011-10-01 48 views
3
Formatter fmt=new Formatter(); 
Calendar cal=Calendar.getInstance(); 
fmt.format("%tc",cal); 
System.out.print(fmt); 

//而不是System.out.print(fmt);我想打印的fmtJTextArea。但價值,因爲我們知道JTextArea只接受字符串value.So我怎麼能轉換成Formatter fmt相當於String value我如何執行以下轉換?

回答

3
textField.setText(fmt.toString()); 
3

退房Formatter.toString()

Formatter fmt = new Formatter(); 
Calendar cal = Calendar.getInstance(); 
yourTextarea.setText(fmt.format("%tc",cal).toString()); 

更少的代碼,如果你使用String.format()它創建了一個Formatter內部:

Calendar cal = Calendar.getInstance(); 
yourTextarea.setText(String.format("%tc", cal)); 

如果你打算這樣做多次,您可能還需要要使用append()而不是setText()作爲不替換您的JTextArea中的任何以前的內容,probab請附加System.getProperty("line.separator")的值以獲得像println()那樣的領先換行符。

+1

而不是'\ r \ n'我推薦'System.getProperty(「line.separator」)'。 – corsiKa

+0

的確,我編輯了我的答案以代替它 –

0

只需撥打fmt.toString()這將給你一個正常的字符串(System.out.print內部做同樣的事情)。