I have a simple JavaFX window with a TextField for users to enter a file path and a separate browse link.
JavaFX Window
I'd like to ask how to extract the full file path of the selected file from JavaFX FileChooser (so I can set the path in the TextField)?
I understand what I'm trying to achieve can be done simply with Swing JFileChooser with something like:
JFileChooser chooser = new JFileChooser();
String someString = chooser.getSelectedFile().toString();
But since my application is in JavaFX I want it to have a consistent look and not a mix with Swing.
I've looked through the documentation, there doesn't seem to be a method for this https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html
Thanks in advance.
Here's another documentation. What you get in return from using showOpenDialog is a File object.
public File showOpenDialog(Window ownerWindow)
Shows a new file open dialog. The method doesn't return until the
displayed open dialog is dismissed. The return value specifies the
file chosen by the user or null if no selection has been made. If the
owner window for the file dialog is set, input to all windows in the
dialog's owner chain is blocked while the file dialog is being shown.
A file object has various methods like e. g. getAbsolutePath.
Use showOpenDialog or showSaveDialog (depending on whether you want to open an existing file or save a new one). Both return a File object.
In the controller class where you have the TextField you can create a method like so:
public void getTheUserFilePath() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Upload File Path");
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("ALL FILES", "*.*"),
new FileChooser.ExtensionFilter("ZIP", "*.zip"),
new FileChooser.ExtensionFilter("PDF", "*.pdf"),
new FileChooser.ExtensionFilter("TEXT", "*.txt"),
new FileChooser.ExtensionFilter("IMAGE FILES", "*.jpg", "*.png", "*.gif")
);
File file = fileChooser.showOpenDialog(dialogPane.getScene().getWindow());
if (file != null) {
// pickUpPathField it's your TextField fx:id
pickUpPathField.setText(file.getPath());
} else {
System.out.println("error"); // or something else
}
}
Related
I am trying to save image in a user selected format from FileChooser SaveDialog. Here's my code:
java docs says the same thing for both get and set methods I dont get it.
File f1 = new File("C:\\Users\\KIRAN\\Desktop\\Andromeda1.png");
FileChooser stegoImageSaver = new FileChooser();
stegoImageSaver.setTitle("Save Image File");
stegoImageSaver.setInitialDirectory(new File("C:\\"));
stegoImageSaver.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("PNG Files", "*.png"),
new FileChooser.ExtensionFilter("BMP Files", "*.bmp"),
new FileChooser.ExtensionFilter("GIF Files", "*.gif"));
File f1 = stegoImageSaver.showSaveDialog(null);
ImageIO.write(img, "png", f1);
What i need is to get the extension from user from the "filechooser save dialog"
and write the image with that extension.
I don't know how to use get&set extension methods in Filechooser in javaFx and couldn't find the practical implementation.
See my last line of code: I want to know how to change the "png" to whatever extension selected by the user from the "fileChooser save dialog".
Thanks in advance.
The selected extension filter is only what the user selects from the combo box (or similar) in the dialog. This may or may not match the actual extension of the file. E.g. with windows you can select the png filter, but use the keyboard to input xyz.gif.
You should get the ending from the file returned from showSaveDialog:
File f1 = stegoImageSaver.showSaveDialog(null);
if (f1 != null) {
String name = f1.getName();
String extension = name.substring(1+name.lastIndexOf(".")).toLowerCase();
ImageIO.write(img, extension, f1);
}
In a simple way, after you define ExtensionFilters you need, you can add them
by this line
"fileChooser.getExtensionFilters().addAll(ex, exx);"
When click save the window will open and you can choice the extension that you need
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter ex = new FileChooser.ExtensionFilter("jpg_Image", "*.jpg"); //Add as you need
FileChooser.ExtensionFilter exx = new FileChooser.ExtensionFilter("GIF", "*.gif"); //Add as you need
fileChooser.getExtensionFilters().addAll(ex, exx);
File file = fileChooser.showSaveDialog(null);
if (file != null) {
ImageIO.write (SwingFXUtils.fromFXImage( myImgView.getImage(),null), "png", file);
}
you can put any default extension in the last line but you still can choose from the extensions that you defined.
I am trying to change a program I wrote a while ago. Currently the program handles a few BufferedReader and BufferedWriters with some logic built in. Let me explain how it used to work.
Class used to upload a file:
public void getFile(){//Used to upload the ACH file.
while(uploadApproval==false){//While upload approval has not been given..
JFileChooser chooser = new JFileChooser();//Creates a new object of the JFileChooser class.
uploadFile = chooser;//Saves the upload file variable as the chooser response.
FileNameExtensionFilter filter = new FileNameExtensionFilter("ACH Files", "ach");
//Sets the allowed file formats for upload.
chooser.setFileFilter(filter);//Activates the created file filter.
chooser.setDialogTitle("Please choose ACH file to upload");//Sets the title bar text.
//Completes once the user clicks ok.
int returnVal = chooser.showOpenDialog(chooser);//
if(returnVal == JFileChooser.APPROVE_OPTION){
uploadApproval=true;
}else{
System.exit(0);
}
}
}
Class used to set directory
public void setDirectory(){//Used to set the directory.
while(saveApproval==false){//While the user does not have approval of the save location..
JFileChooser chooser2 = new JFileChooser();//Creates a new JFileChooser object.
saveFile = chooser2;//Sets the save file location to chooser2.
chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//User is only able to scan for
//directories.
//Completes once the user clicks okay.
int returnValue2 = chooser2.showDialog(chooser2, "Directory to save");
if(returnValue2 == JFileChooser.APPROVE_OPTION){
saveApproval=true;
}else{
System.exit(0);
}
}
}
Then later I begin the actual buffered reader/writer process which involves a lot of logic here:
location = "//NachaOutput"+randomNumber+".ACH";
try{
String sCurrentLine;//String representing the current line.
//Pulls the uploaded file.
br = new BufferedReader(new FileReader(NachaMain.uploadFile.getSelectedFile()));
bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
Now here is what I need to do. I have been asked to remove the screen where the user selects the directory from the beginning. Instead, the user will select the save directory in the end of the process.
This means that the "SetDirectory" method won't be called at all, therefore this line of code:
bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
obviously won't work. I need to find some way to replace that file writer location with a generic location that would be the same for all users regardless of their setup. Something along the lines of documents.
I tried doing this:
bw = new BufferedWriter(new FileWriter("Libraries\\Documents"+location));
but got an exception about an invalid path.
So please help me out and let me know a good path that I could save the file to automatically. That saved file will basically be a "dummy" file. Later in the end of the program I will copy that dummy file to the location the user specifies then delete it, so the location really doesn't matter too much.
Thanks in advance!
You could create a temporary file using File.createTempFile(). It might make cleanup easier if you called deleteOnExit() for the created temporary file.
I'm using JFileChooser API for opening a file. When open dialogbox appears, it does not show images for various option like, Up one lever, Create new Folder, List, Details. Some of the option is also not visible untill mouse hover. Here is the image :
My code looks something like this:
JFileChooser fileChooser = new JFileChooser();
FileFilter xlsExcelType = new FileNameExtensionFilter("Excel spreadsheet (.xls)", "xls");
FileFilter xlsxExcelType = new FileNameExtensionFilter("Excel spreadsheet (.xlsx)", "xlsx");
fileChooser.addChoosableFileFilter(xlsExcelType);
fileChooser.addChoosableFileFilter(xlsxExcelType);
fileChooser.setFileFilter(xlsxExcelType);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file= fileChooser.getSelectedFile();
}
Kndly pass your idea to make those option visible with image.
Thanks
Look and see if java.awt.FileDialog has the option(s) you want. If not, you might try ideas from here or here.
I made a button that will create a JFileChooser so the user can open a .txt file, here's the code inside the action listener of the button:
JFileChooser fc = new JFileChooser();
//filter-show only .txt files
FileNameExtensionFilter txtfilter = new FileNameExtensionFilter("txt files (*.txt)", "txt");
//apply the filter to file chooser
fc.setFileFilter(txtfilter);
fc.setDialogTitle("Otvori txt file");
//disable the ability to show files of all extensions
fc.setAcceptAllFileFilterUsed(false);
//create file chooser via jFrame
fc.showOpenDialog(jFrame);
//get selected file
File selFile = fc.getSelectedFile();
Path path = Paths.get(selFile.toString());
asdf = selFile.toString();
//display chosen file on jLabel5
jLabel5.setText(path.getFileName().toString());
It works just fine, if you select the .txt file inside the file chooser, but it also works if you just select a file and then press cancel and exit. I assume it's because of the getSelectedFile() but I am wondering if there is a way to make sure the user selected a file and pressed open inside file chooser as a condition to get a file?
You should check whether the return value from:
fc.showOpenDialog(jFrame) == JFileChooser.APPROVE_OPTION
That return value indicates how the user exited the dialog.
See JFileChooser.showOpenDialog(Component) docs.
i need help regarding the save menu item i have in my menu bar. i have set the code to
private void smActionPerformed(java.awt.event.ActionEvent evt) {
}
but i am unsure what needs to go inbetween the brackets? The gui is a form where poeple fill in there medical record e.g combo box "mr/mrs" textfield "medical problems" etc and when they click file save i would like the user to get a save box (like save as box in word) and the information to be saved in a txt file.
P.S. would it be possible to have the "file type" set to save as a txt file as default.
Use JFileChooser#showSaveDialog() to ask the enduser to select a File.
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// ...
} else {
// User pressed cancel.
}
Maybe looking at this could help you. I don't fully understand what you need.
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFileChooser.html
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html