[英]How to output all of the text in my JtextArea to a save file?
您好,其他堆垛車! 我在為游戲創建適當的保存功能時遇到問題。 我遇到的主要問題是捕獲名為display的J文本區域內的所有數據。 顯示屏反映了到目前為止游戲中已采取的動作,顯示屏頂部顯示“ Welcome to Togiz Kumalak”。
我的問題是,當我保存游戲時,它僅將文本的第一行記錄到文件中,而不是所有行中。
一個例子是:
Welcome to Togiz Kumalak
Player 1 Cup 1
Player 2 Cup 3
等等。 當我保存文件時,只會顯示第一行。
這是保存偵聽器的當前代碼。
class SaveListener implements ActionListener
{
String a = display.getText();
JFileChooser myChooser= new JFileChooser();
public void actionPerformed(ActionEvent event)
{
String fileName;
myChooser.setCurrentDirectory(new File("."));
myChooser.showSaveDialog(null);
fileName = myChooser.getSelectedFile().getPath();
try
{
OutputStream file = new FileOutputStream(fileName);
PrintStream printStream = new PrintStream(file);
printStream.print(a);
printStream.close();
/* Version 11, 23.1. Scroll pane and text area support when saving. */
}
catch(IOException e)
{
System.out.println("Problem making or writing to an output stream.");
System.out.println(e);
}
}
}
使用JTextArea API的write(...)
方法,而不是嘗試創建自己的方法。
..在為我的游戲創建適當的保存功能時遇到問題
給定“適當”一詞(我的重點是),我必須指出,保存/加載游戲的正確方法是根據“游戲狀態模型”,而不是根據“游戲狀態模型粗化為文本行”。
可以根據數據的復雜性以多種方式保存該游戲狀態模型,但與該方法使用的序列化方法相比,應使用非常不同的序列化方法(在我們的代碼中對數據進行編碼/解碼的工作量更少)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.