Search code examples
javaswingfile-iojbuttonstring-parsing

Java GUI - storing input/calculations into txt tile


I've got a project where I need to get user input and then perform a volume calculation, all of which I have accomplished for a few different shapes. However, I need to be able to store the input and calculation into a file for each shape into a file from which I can read later if selected. I've tried to do this a few different ways, to no avail. All of which have gave me a syntax error except for my latest try. This try, however, doesn't seem to write to a file and only returns 0.0 on a single line. Any help would be appreciated

public JButton getCalculateButton()
{
    JButton spa; 
    spa = new JButton("Calculate Volume");
    spa.setMnemonic('C');
    spa.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e)
        {               
            DecimalFormat num = new DecimalFormat(",###.##");
            double length, depth, volume;
            String instring;

            instring = lengthField.getText();
            if (instring.equals("")){
                instring = "0";
                lengthField.setText("0");
            }
            length = Double.parseDouble(instring);

            instring = depthField.getText();
            if (instring.equals("")){
                instring = "0";
                depthField.setText("0");
            }
            depth = Double.parseDouble(instring);

            volume = length * 8 * 4.8284 * depth;
            volumeField.setText(num.format(volume));

        }
    });
    return spa;
}

public JButton getSaveButton(){
    JButton save; 
    save = new JButton("Save Data");
    save.setMnemonic('C');
    save.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

            PrintWriter writer;
            try {
                writer = new PrintWriter(new FileWriter("spaFile.txt"));
                writer.printf(String.valueOf(length), String.valueOf(depth), String.valueOf(volume));
                writer.close();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }           
    });

    return save;
}

That is part of my GUI, that does the calculation and hopefully would have stored the data, but doesn't.

public JButton getSearchButton()
{
    JButton search; 
    search = new JButton("Search");
    search.setMnemonic('S');
    search.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e)
        {               
            FileInputStream fileStream;
            try {
                fileStream = new FileInputStream("spaFile.txt");
                 DataInputStream in = new DataInputStream(fileStream);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    System.out.println(reader.readLine());
                    reader.close();
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
    });
    return search;
}

}

That is the part to read, though I don't have it fully as a GUI yet for testing purposes.


Solution

  • I'm not sure you really want

    writer.printf(String.valueOf(length), String.valueOf(depth),
        String.valueOf(volume));
    

    in the ActionListener of the save button. That statement uses String.valueOf(length) as the string that will be formatted and everything after it as formatting specifications; you probably want

    writer.printf(String.valueOf(length) + ", " + String.valueOf(depth) +
        ", " + String.valueOf(volume));
    

    Also: if you access length, depth and volume, make sure you're in a scope that can actually see those variables. If your values show up as 0.0 for all of those, that means you didn't assign the values you want them to have in the place where you read in those values.


    Here's some code I recently used to save some information in a .txt file:

    try {
            FileWriter writer = new FileWriter(path);
    
            for (Movie movie : movies) {
                writer.write(movie.toString() + LINE_SEPARATOR);
            }
    
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    

    The variables' names hopefully are telling you what their purpose is. Note: this will overwrite the content of the file every time you use the code; to append stuff to the file, use Writer#append(..); see the docs on that (note that you probably want some specific Writersubclass, not the generic one).