When click “Save to File” button, then write the records from ArrayList to file product.txt, at the same time display "file write success" in JTextArea on the GUI
时间: 2024-03-03 07:51:37 浏览: 77
Java Swing JTextArea文本区域的实现示例
5星 · 资源好评率100%
Sure, I can help you with that! Here is the code snippet that you can use to achieve this functionality:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JTextArea;
public class WriteToFile {
public static void writeToFile(ArrayList<String> records, JTextArea textArea) {
try {
FileWriter writer = new FileWriter("product.txt");
for (String record : records) {
writer.write(record + "\n");
}
writer.close();
textArea.setText("File write success");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
This code defines a static method `writeToFile` that takes an `ArrayList` of `String` objects and a `JTextArea` as input parameters. It then creates a `FileWriter` object to write the records to the file "product.txt" and displays "File write success" in the `JTextArea`.
To use this method, you can simply call it when the "Save to File" button is clicked, and pass in the `ArrayList` of records and the `JTextArea` object. For example:
```java
saveToFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
WriteToFile.writeToFile(records, textArea);
}
});
```
I hope this helps! Let me know if you have any further questions.
阅读全文