Question

Hello there fellow stackers! I'm having a problem creating a proper save function for my game. The main problem I am having is capturing all of the data inside of my J text area named display. The display reflects what moves have been made so far in the game, and at the top of the display it says "Welcome to Togiz Kumalak".

My problem is that when I save the game, it only records the first line of text to the file instead of all lines.

an example is:

            Welcome to Togiz Kumalak
            Player 1 Cup 1
            Player 2 Cup 3

and so on. When I save the file, only the top line will be shown.

Here is my current code for the save Listener.

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);
        }
    }
}
Was it helpful?

Solution

Use the write(...) method of the JTextArea API instead of trying to create your own method.

OTHER TIPS

..having a problem creating a proper save function for my game

Given the word 'proper' (my emphasis) I have to point out that the proper way to save/load games is according to a 'game state model' as opposed to a 'game state model crudely translated to lines of text'.

That game state model might be saved a number of ways depending upon the complexity of the data, but should use very different serialization methods (with less work done encoding/decoding the data in our code) than this approach uses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top