所以基本上我有这段代码形成了一个简单的 JFrame 程序,它将值(花名,LOL)存储到一个列表中并显示该列表。但我只是不知道如何使它将列表保存到 .txt 文件并在启动时加载它。这可能是一个没有脑子的,但我就是不明白,不知道从哪里开始
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());
}
}
}
}