Java Swing - Finder Text Box - java

I current have a JFrame application that uses JTextField's for input of file location as per the code below.
txtSource = new JTextField();
txtSource.setToolTipText("/location/of/file/test.txt");
txtSource.setText("/location/of/file/test.txt");
txtSource.setBounds(16, 122, 412, 29);
contentPane.add(txtSource);
txtSource.setColumns(10);
What I would like to do is allow a directory search for the user to select the location of the file on the local computer and that location would populate into the Textbox.
I found the below information on JCHooser, but I'm not sure if this is way to go and would like assistance on how to implement.
String filename = File.separator+"tmp";
JFileChooser fc = new JFileChooser(new File(filename));
// Show open dialog; this method does not return until the dialog is closed
fc.showOpenDialog(frame);
File selFile = fc.getSelectedFile();
// Show save dialog; this method does not return until the dialog is closed
fc.showSaveDialog(frame);
selFile = fc.getSelectedFile();
Thanks in advance

Use
int option = fc.showOpenDialog(frame);
if (option == JFileChooser.APPROVE_OPTION) {
txtSource.setText(fc.getSelectedFile().getAbsolutePath())
}
populates the text field with the selected file absolute file location

Related

JAVA | Saving file path

So I wanted to save files needed for the program, but the user has to decide where to save files... But because I dont want the user to select the path everytime he starts the program, the program should save the path where to go to find the files, how to?
I made the user select the file with a JFileChooser.
JButton jButton = new JButton();
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
jFileChooser.setDialogTitle("Choose your Path!");
jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(jFileChooser.showOpenDialog(jButton) == JFileChooser.APPROVE_OPTION){
}
path = jFileChooser.getSelectedFile().getAbsolutePath();
pathBind = jFileChooser.getSelectedFile().getAbsolutePath() + "/binds.jar";
bindFile = new File(pathBind);
If any further information is needed, I'll give it... Sorry if I forgot something^^.
That kind of information probably belongs in user preferences, which you access using the Preferences class:
private static final String LAST_SAVE_DIR_PREFS_KEY = "last-save-dir";
private static final Preferences PREFERENCES =
Preferences.userNodeForPackage(MyUserInterface.class);
// ...
String saveDir = PREFERENCES.get(LAST_SAVE_DIR_PREFS_KEY,
System.getProperty("user.home"));
jFileChooser.setSelectedFile(new File(saveDir));
jFileChooser.setDialogTitle("Choose your Path!");
jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (jFileChooser.showOpenDialog(jButton) == JFileChooser.APPROVE_OPTION) {
PREFERENCES.put(LAST_SAVE_DIR_PREFS_KEY,
jFileChooser.getSelectedFile().toString());
// ...
}

How to save Image in a user selected format using FileChooser in javaFx?

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.

How to get file path from JavaFX FileChooser?

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
}
}

How to set the last path as the next default using JFileChooser

I have several dialog boxes which provide a File Chooser. For the first, my coding was like this
JFileChooser chooser= new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal= chooser.showOpenDialog(this);
if(returnVal==JFileChooser.APPROVE_OPTION){
File f= chooser.getSelectedFile();
jTextField1.setText(f.getPath());
chooser.setCurrentDirectory(f);
}
In my case, i would like to set the last path which is selected as the default path in next selection JFileChooser. Is there any solution for me?
Thanks for any response
Depending on your requirements, you can use Preferences to store it away and use it again after the program has been restarted.
Preferences pref = Preferences.userRoot();
// Retrieve the selected path or use
// an empty string if no path has
// previously been selected
String path = pref.get("DEFAULT_PATH", "");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Set the path that was saved in preferences
chooser.setCurrentDirectory(new File(path));
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File f = chooser.getSelectedFile();
chooser.setCurrentDirectory(f);
// Save the selected path
pref.put("DEFAULT_PATH", f.getAbsolutePath());
}
You will have to "remember" the last path.
This can easily be done by storing the value in a instance variable...
private File lastPath;
//...
lastPath = f.getParentFile();
And simply resetting it when you need to...
//...
if (lastPath != null) {
chooser.setCurrentDirectory(lastPath);
}
You could also use a single instance of the JFileChooser, so each time you show it, it will be at the last location it was used...

java - JFileChooser - open/cancel/exit button

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.

Categories