entering the name or select it again, so all what they need to do is press save button.
I did not find a way to do that in netbeans since I am new to netbeans and to java too, but I thought I can do this in this way :
1- when the user open the file, I can get the path or the name of the file and store it in a private field in the class.
2- when the user press the save button, I open a file and write the text to it, and save it as the name of the opened file, by using get method.
but this way write nothing to the file and stay empty or has no change.
this is part of my code
public class SheefraTest1View extends FrameView {
private String currentFile;
public void setCurrentFile(String file){
currentFile = file;
}
public String getCurrentFile(){
return currentFile;
}
and this is the method when I used the currentFile
private void openFileActionPerformed(java.awt.event.ActionEvent evt) {
int option = JOptionPane.showConfirmDialog(null, "Want to save this file ? ");
if(option == 0){
// Yes = save and open a new one
int returnValSave = jFileChooser.showSaveDialog(null);
//save the file
if (returnValSave == JFileChooser.APPROVE_OPTION) {
File fileSave = jFileChooser.getSelectedFile();
saveToFile(fileSave, jTextArea);
jTextArea.setText("");
//open a file
int returnValOpen = jFileChooser.showOpenDialog(null);
if (returnValOpen == JFileChooser.APPROVE_OPTION) {
File fileOpen = jFileChooser.getSelectedFile();
setCurrentFile(fileOpen.getAbsoluteFile().toString()); //used to store the current file
readFromFile(fileOpen, jTextArea );
}else {
//cancel
}
}else{
//cancel = do nothing
}
}else if(option == 1){
// No == don't save and open new one
jTextArea.setText("");
int returnValOpen = jFileChooser.showOpenDialog(null);
if (returnValOpen == JFileChooser.APPROVE_OPTION) {
File fileOpen = jFileChooser.getSelectedFile();
readFromFile(fileOpen, jTextArea );
}else {
//cancel
}
}else{
// Canceld do nothing
}
}
and finally this is the saveToFile() method
public void saveToFile(File file, JTextArea txt){
try{
FileWriter userFile = new FileWriter(file);
BufferedWriter outBuff = new BufferedWriter(userFile);
String str = "string for example";
outBuff.write(str);
outBuff.close();
txt.setText(""); // to empty the textArea after the file saved
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
}
Please if somebody can find where is the error in here or if there is better way to save a file without selecting it again, thank you so much for your help.

New Topic/Question
Reply



MultiQuote







|