JTextField 不接受超过 1 个输入

JTextField not accepting more than 1 input

我想这样做,这样当我 运行 这个程序时,我可以继续从文本字段输入输入,它会打印到我们正在尝试写入的文件。

到目前为止,我的代码仅在我第一次点击 'Enter' 时有效。 之后,当我再次这样做时,它会抛出异常。

有人能帮我吗?

public static void main(String [] args) throws IOException {

    //creates file or opens existing file
    File f = new File("C:/Users/User/Desktop/course.txt");
    Scanner sc = new Scanner(System.in);
    FileWriter w = new FileWriter(f.getAbsoluteFile(), true);
    BufferedWriter r = new BufferedWriter(w);

    //GUI Setting
    JFrame frame = new JFrame();
    JLabel text = new JLabel();
    JLabel results = new JLabel();
    JPanel panel = new JPanel();
    JTextField textField = new JTextField();

    textField.setPreferredSize(new Dimension(450, 30));
    text.setText("Enter \"END\" to terminate program OR \"CLEAR ALL\" to delete everything in the file");

    frame.getContentPane().add(panel);
    frame.setSize(new Dimension(500, 150));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Course");
    frame.setResizable(true);
    frame.setVisible(true);

    panel.add(text);
    panel.add(textField);
    panel.add(results);

    //action listener for textfield when user hits enter
    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String message;
                message = textField.getText();
            try {
                    if(message.contains("END")) {
                        System.exit(0);
                    }
                    if(message.contains("CLEAR ALL")) {
                            clear();
                    }
                    else {
                            r.write(message);
                            r.newLine();
                    }
                    r.close();
                }catch(IOException e1) {
                    results.setText("Error");
                }
            textField.setText("");
        }
    }
);

    //set focus to text field once GUI is opened
    SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            textField.requestFocus();
          }
        });
}

//clear function to empty the file
private static void clear() throws FileNotFoundException {
    File f = new File("C:/Users/User/Desktop/course.txt");
    PrintWriter w = new PrintWriter(f);
    w.print("");
    w.close();
}
}

问题很简单。您在 BufferedWriter 上呼叫 close

else {
   r.write(message);
   r.newLine();
}

r.close();

BufferedWriter#close 的 Javadoc 状态

Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.


您还使用两个不同的对象写入同一个文件。我建议你坚持使用一个而放弃另一个。