所以基本上我有这段代码,它形成了一个简单的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());
}
}
}
}
你可能应该从1)加载一个文件以填充Flower类结构中的字符串列表花朵2)然后在关闭操作上添加一个操作侦听器,而不是关闭时的默认退出,以便将列表另存为文件3)最后,您应该确保文件存在然后创建。