JavaFX Saving A File with File Browser Dialog
This program shows how to prompt the user to save a file with a file-browser like dialog using JavaFX FileChooser
.
JFXSaveBrowse.java
package ceccs;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.FileWriter;
public class JFXSaveBrowse extends Application {
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
TextField textField = new TextField("type some stuff to save");
Button saveButton = new Button("Save");
Label msgLabel = new Label("Save Your File");
saveButton.setOnAction(event -> {
FileChooser fc = new FileChooser();
File file = fc.showSaveDialog(primaryStage);
if(file.exists() == false) {
try{
file.createNewFile();
FileWriter fWriter = new FileWriter(file);
fWriter.write(textField.getText());
fWriter.close();
msgLabel.setText(file.getName() + " was created");
} catch (Exception ex) {
System.out.println(ex);
}
} else {
msgLabel.setText("ERROR: FILE EXISTS ALREADY!");
}
});
VBox root = new VBox(textField,saveButton, msgLabel);
root.setSpacing(10);
Scene scene = new Scene(root, 400, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
}