gpt4 book ai didi

java - JTextField 不接受超过 1 个输入

转载 作者:行者123 更新时间:2023-12-02 10:12:00 26 4
gpt4 key购买 nike

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

到目前为止,我的代码仅在我第一次按“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.

<小时/>

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

关于java - JTextField 不接受超过 1 个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54951423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com