1

How can i save the information that is entered into each text box so that after the app is closed it remembers the next time i open up the app, when entering in the text box it remembers what was put in there before?

I know of the act of creating a text file and then next time it opens up it reads that file. im not sure if that is the solution for this, but if it is, i do not know how i would do that. Code Below:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class RecipeFinder {
public static void main(String[] args) {

//JFrame
    JFrame frame = new JFrame("The Recipe Finder");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(500,400));


//JPanel
    JPanel entry = new JPanel();
    entry.setLayout(new BoxLayout(entry, BoxLayout.Y_AXIS));

//JLabel
    JLabel insert = new JLabel("Insert Food/Ingredients");
    entry.add(insert);

//JTextField(s)
    JTextField foodOne = new JTextField();
    foodOne.setPreferredSize(new Dimension(200,24));
    entry.add(foodOne);
    JTextField foodTwo = new JTextField();
    foodTwo.setPreferredSize(new Dimension(200,24));
    entry.add(foodTwo);

//JButton(s)
    JButton addTextBox = new JButton("Add");
    addTextBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JTextField newBox = new JTextField();
            newBox.setPreferredSize(new Dimension(200,24));
            entry.add(newBox);
            entry.revalidate();
            frame.invalidate();
        }
    });
    JButton search = new JButton("Search Recipes");
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(addTextBox);
    buttonPanel.add(search);
    JPanel rootPanel = new JPanel();
    rootPanel.setLayout(new BorderLayout());
    rootPanel.add(entry, BorderLayout.CENTER);
    rootPanel.add(buttonPanel, BorderLayout.SOUTH);

    JScrollPane rootEntry = new JScrollPane(rootPanel);
    rootEntry.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    rootEntry.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);


//FrameWork
    frame.add(rootEntry);
    frame.pack();
    frame.setVisible(true);

}

}

1 Answers1

0

Simplest way how to do it is Java serialization. You need a holder class witch implemetns Serializable inteface. It can be a pojo with string fields or List for any number of strings. Then you fill this object with data from text fields. Filled object can stored and restored to/from disk as described here How to write and read java serialized objects into a file

Peter Šály
  • 2,848
  • 2
  • 12
  • 26