java - JFileChooser - open/cancel/exit button - java

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.

Related

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

Swing - JFileChooser open dialog does not show images for various options

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.

JFileChooser that manually picks the file

I was just wondering. Is there any way to use JFileChooser but open the file manually? So I could put the directory somewhere in code before and then just load it?
Here is part of my code:
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
File plik = fc.getSelectedFile();
Scanner skaner = new Scanner(plik);
while (skaner.hasNext())
dialog.append(skaner.nextLine() + "\n");
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
So I want to:
Open file from directory so i won't have to choose the "something.txt".
Piece of code that let me open another file in the same JTextArea one by one, by clicking the JButton.
What I really need is a piece of code that lets me load txt file (from directory) by clicking a button few times in a row.
Is this even possible?
You can use setSelectedFile method of the JFileChooser to 'pre-select' the File, the user will only have to click OK if the file exists.
JTextArea directory=new JTextArea();
directory.setText(System.getProperty("user.home"));
directory.setEditable(true);
JFileChooser choose=new JFileChooser(directory.getText());

Using JFileChooser without opening the actual file

I'm using the JFileChooser to allow a user to choose a .txt file that will later be processed by my program, however when the user chooses the file, it is actually opened by my computers default app (in my case TeXworks) as well as used by my program. Any idea how I can stop this?
File fileToOpen = fileChooser.getSelectedFile();
JFileChooser's getSelectedFile() method, returns a File object.
Use the getAbsolutePath() to get the absolute name to the file.
Modified example from the JavaDoc:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open this directory: " + chooser.getSelectedFile().getAbsolutePath());
}
So in your case you just need to append .getAbsolutePath() to the end of your statement, like this:
File fileToOpen = fileChooser.getSelectedFile().getAbsolutePath();

Categories