我正在搞java swing,並試圖用JTextArea打開一個包含現有數據的文本文件。無論我嘗試過不同的事情,它似乎都不會保存任何更改。在JTextArea中打開,編輯和保存文本到.txt文件
下面是讀取文本文件的代碼,但不寫(顯然)。
如果有人可以請我告訴我如何成功地保存對JTextArea的更改,我會非常感激。
package funwithswing;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AllDataGUI extends JFrame{
public AllDataGUI(){
fileRead();
panels();
}
private String storeAllString="";
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Viewing All Program Details");
private JTextArea textArea = new JTextArea(storeAllString,0,70);
private JButton getCloseButton(){
return closeButton;
}
private void fileRead(){
try{
FileReader read = new FileReader("CompleteData.txt");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp=scan.nextLine()+"\n";
storeAllString=storeAllString+temp;
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
private void fileWrite(){
try{
FileWriter write = new FileWriter ("CompleteData.txt");
textArea.write(write);
}
catch (Exception e){
e.printStackTrace();
}
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JTextArea textArea = new JTextArea(storeAllString,0,70);
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
});
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
private void saveBtn(){
}
}
謝謝Arijit。如何添加一個彈出框來表示該項目已成功關閉? – Splunk
JOptionPane.showMessageDialog(this,「Saved」);在正確的地方使用此代碼。 – Arijit
謝謝。你幫了我很多。 – Splunk