JFileChooser click programmatically on open - java

I have following code to open a JFilechooser
chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
chooser.showOpenDialog(null);
String path = chooser.getSelectedFile().getPath();
What I want to do is programmatically close this dialog. I see the open button, but how can I "press" it programmatically?

This will simulate the user selection and opening of a file:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(YourApplication.class.getName()).log(Level.SEVERE, null, ex);
}
chooser.setSelectedFile(new File("/your/file/path")));
chooser.approveSelection();
}
}).start();
chooser.showOpenDialog(null);
String path = chooser.getSelectedFile().getPath();
The Thread.sleep(100) is ugly, but has to be in there because otherwise, the JFileChooser isn't open yet when approveSelection is called.

Related

How To Open File Dialog And Create File On It?

1
I opened File Dialog but I don't create the file on it? How?
JFileChooser fileChooser = new JFileChooser();
File selectedFile = null;
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (**result == JFileChooser.APPROVE_OPTION**) {
selectedFile = fileChooser.getSelectedFile();
} else {
confirmExit();
return;
}
To save a file with JFileChooser, you need to use the showSaveDialog() method instead of the showOpenDialog() like in your snippet. For more information check out How to use File Choosers and check out the JFileChooser JavaDoc.
Then the next step if the saving has been approved, is to actually write the file.
For this, you can use a FileWriter.
I put together a small snippet, which opens a JFileChooser on a button click, where you can provide the filename, where some String will be written to this file.
Example:
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> buildGui());
}
private static void buildGui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton btn = new JButton("Save your File");
// action listener for the button
btn.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser(); // create filechooser
int retVal = fileChooser.showSaveDialog(frame); // open the save dialog
if (retVal == JFileChooser.APPROVE_OPTION) { // check for approval
// create a bufferedwriter with the specified file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) {
// write the content to the file
writer.write("Your content that shall be written to the file");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
panel.add(btn);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Output:

JFileChooser can select any folder apart from the current one?

I am using JFileChooser to allow the user to select a folder. They must be able to view the files in each folder for context. The problem is that I can't select the folder I am when the dialog pops up. (i.e. I click "open" and nothing happens). However, if I switch to another directory and then back to the first one, then I can select it.
public static String selectFolder()
{
final JFileChooser chooser = new JFileChooser() {
public void approveSelection() {
if (getSelectedFile().isFile()) {
return;
} else
super.approveSelection();
}
};
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Select Folder");
chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
chooser.setAcceptAllFileFilterUsed(false);
chooser.showOpenDialog(null);
File x = chooser.getSelectedFile();
if( x != null )
return x.toString();
return null;
}
public static String selectFolder() {
final JFileChooser chooser = new JFileChooser() {
public void approveSelection() {
if (getSelectedFile().isFile()) {
return;
} else
super.approveSelection();
}
};
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Select Folder");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
chooser.setSelectedFile(new java.io.File("."));
chooser.showOpenDialog(null);
File x = chooser.getSelectedFile();
if (x != null)
return x.toString();
return null;
}
you only have to add the line:
chooser.setSelectedFile(new java.io.File("."));
for the sake of being user-friendly, set it to the same as the CurrentDirectory, so that the user sees which directory will be selected when he clicks the button
As per JFileChooser you have to choose a file or folder on the dialog then only it will allow you to click open/save.

How to restrict file choosers in java to specific files?

private void openMenuActionPerformed(java.awt.event.ActionEvent evt) {
DBmanager db = new DBmanager();
if (!db.getCurrentUser().equals("Admin")) {
JOptionPane.showMessageDialog(this, "You are Not Allowed to Run Applications");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("MS Office Documents", "docx", "xlsx", "pptx"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().open(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if (db.getCurrentUser().equals("Admin")) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().open(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}// TODO add your handling code here:
}
I am trying to filter files in a file filter by setting fileChooser.setAcceptAllFileFilterUsed(false);. The "all files" option disappears from the FileChooser but all files remain visible unless you select an option from PDF documents,ms Office or images. I want to have only my 3 custom filters upon opening the file chooser.
For example, if you want to filter your JFileChooser to strictly display most commonly found image files, you would use something like this:
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "gif", "jpeg");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(filter);
The first argument is the description (what gets displayed upon selection at the bottom) and the second argument are the informal file extensions.
You can use FileNameExtensionFilter to add allowed extensions to your FileChooser dialog. Here's an example:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
For more info, please refer to the Javadocs: FileNameExtensionFilter
In my case, I had to put the
setFileFilter(
new FileNameExtensionFilter("Default file filter", ...)
);
after all other calls to the method
addChoosableFileFilter(...);
to make setAcceptAllFileFilterUsed(false) works.
This works fine in java8.1
JFileChooser dbfilechooser = new JFileChooser();
FileNameExtensionFilter filter1 =
new FileNameExtensionFilter("xls","xls");
FileNameExtensionFilter filter2 =
new FileNameExtensionFilter("xlsx", "xlsx");
FileNameExtensionFilter filter3 =
new FileNameExtensionFilter("csv", "csv");
dbfilechooser.addChoosableFileFilter(filter1);
dbfilechooser.addChoosableFileFilter(filter2);
dbfilechooser.addChoosableFileFilter(filter3);

JFileChooser component display weird

I'm trying to open a file in filechooser dialog, however, when i opened a file or simply close the dialog. The dialog appears again, i have to close it twice. Here is my code, don't know what's wrong with it
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
ObjectInputStream input;
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
input.close();
}
javax.swing.JFrame openFileFrame = new javax.swing.JFrame();
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
this code lines to create first one
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
input.close();
}
and rest of code lines to embeding second one
javax.swing.JFrame openFileFrame = new javax.swing.JFrame();
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);
Remove the first occurrence of openFileChooser.showOpenDialog(null);

Unable to figure how to store "Save As" text in a string and use it

I am new to UI design in Java. I am trying to create a GUI to download a file off the Internet and save it on your hard drive. I have got the code working except for one thing which I want to add. I have added a JFileChooser which lets the user select the destination folder. But I am unable to figure out how to change the filename to the one which user enters in the Save As bar on the JFileChooser menu.
Browse Button
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}
});
Download Button
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(DESTINATION_FOLDER + "/" + filename);
Here filename should be the one which user enters. Pointers on how to get this done?
Actually you don't need to get the FileName from the Save As Bar in the JFileChooser.
Just do like this:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
//Don't use the 'FileSelectionMode();'. Let it be Default.
chooser.setAcceptAllFileFilterUsed(true);
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
file = chooser.getSelectedFile();
//file should be declared as a File.
System.out.println("The location to save is: " + chooser.getCurrentDirectory();));
System.out.println("The FileName is: " + file.getName());
}
}
DOWNLOAD BUTTON:
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(file);
Without seeing more of your code the best I could suggest is to create a Global String in the class you are working in.
public class gui extends JFrame{
public String filePath="";
public static void main(String args[]){
//button code
browseButton.addActionListener(new ActionListener())
saveAsButton.addActionListener(new ActionListener())
URLConnection connection = downloadUrl.openConnection();
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("browseButton"){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: "+chooser.getCurrentDirectory());
filePath = chooser.getCurrentDirectory().toString();
}
else{
//save as button selected
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(filePath);
}
}
}
Add this line:
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
Full code:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}

Categories