So basically I have this piece of code that forms a simple JFrame program which stores values (flower names, LOL) into a list and displays the list. But I just can't figure out how to make it save the list to a .txt file and load it on startup.. this might be a no brainer but I just don't get it, don't know where to start
public class Flower extends JFrame implements ActionListener{
private List<String> flowerNames = new ArrayList<String>();
private JTextArea output;
private JTextField input;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run(){
new Flower().setVisible(true);
}
});
}
public Flower() {
setTitle("Flowers");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(1,2));
JPanel right = new JPanel(new GridLayout(2,1));
JPanel row = new JPanel();
row.add(new JLabel("Flower: "));
row.add(input = new JTextField(25));
right.add(row);
row = new JPanel();
row.add(new JPanel(new FlowLayout()));
JButton button = new JButton("Add");
row.add(button);
right.add(row);
button.addActionListener(this);
getContentPane().add(right);
getContentPane().add(new JScrollPane(output = new JTextArea()));
pack();
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (input.getText().length() > 0){
try {
flowerNames.add(input.getText());
} catch (Exception e){
JOptionPane.showMessageDialog(
this,
"Wrong input!",
"Check the input",
JOptionPane.PLAIN_MESSAGE);
}
finally {
Collections.sort(flowerNames);
StringBuilder sb = new StringBuilder();
for (String input : flowerNames){
sb.append(input.toString() + "\n");
}
output.setText(sb.toString());
}
}
}
}
You should probably start with 1) loading a file to fill the string list flowers in the contructor of your Flower class 2) then adding an action listener on the close operation rather than the default exit on close in order to save the list as file 3) finally you should make sure the file exist then create.