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);
Related
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:
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.
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.
Using following code i can store program.txt in a working project folder, but how can I use JFileChooser or any other option to save file at a selected location?
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
o = new BufferedWriter(new FileWriter("program.txt"));
o.write(t1.getText());
o.write(",");
o.write(t2.getText());
o.write(",");
o.write(t3.getText());
o.write(",");
o.write(t4.getText());
o.write(",");
o.write(t5.getText());
o.write(",");
o.write(t6.getText());
o.write(",");
o.write(t7.getText());
o.write(",");
o.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(aComponent); //parent component to JFileChooser
if (returnVal == JFileChooser.APPROVE_OPTION) { //OK button pressed by user
File file = fc.getSelectedFile(); //get File selected by user
o = new BufferedWriter(new FileWriter(file)); //use its name
...
//your writing code goes here
}
You can do this way by setting File object in JFileChooser object
File f = new File("filename");
myJFileChooser.setSelectedFile(f);
check this post for more
http://www.coderanch.com/t/561950/GUI/java/Save-JTextArea-JFileChooser-TXT-file
I have a JLabel inside which I have saved my ImageIcon like this:
ImageIcon imageIcon = sample.map(); // a map method create an ImageIcon object
imageLabel.setIcon(imageIcon);
imageLabel.setVisible(true);
Now I would like to save this ImageIcon object into a PNG file when clicking on the Save item menu.
private void imageActionPerformed(java.awt.event.ActionEvent evt) {
Icon pic = imageLabel.getIcon();
JFileChooser fileChooser = new JFileChooser("C:/");
fileChooser.setSelectedFile(file);
// this filter will allow just PNG extension
FileFilter filter = new MyCustomFilter2();
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File fileToSave = fileChooser.getSelectedFile();
}
else
{
System.out.println("File access cancelled by user.");
}
}
Yes I know that this code is wrong and some part is missing, I think I should somehow save my Icon object called pic into a File object. This is my assumption. How can I do it please?
Thanks for any help,
Michal.
Here is my source code
private void imageActionPerformed(java.awt.event.ActionEvent evt) {
try{
Icon image = imageLabel.getIcon();
BufferedImage bi = new BufferedImage(image.getIconWidth(),image.getIconHeight(),BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
File file = new File("outputFile");
JFileChooser fileChooser = new JFileChooser("C:/");
fileChooser.setSelectedFile(file);
FileFilter filter = new MyCustomFilter2();
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
ImageIO.write(bi, "PNG", file);
File fileToSave = fileChooser.getSelectedFile();
}
else
{
System.out.println("File access cancelled by user.");
}
}
catch(IOException e){
e.printStackTrace();
}
}
The File object returned by the JFileChooser just represents the location on disk where the user would like to save the file. After that you'll want to use ImageIO.write() to save the file to disk.
e.g.
ImageIO.write(image, "png", file);
If you have an Icon, I think you may need to convert that to a BufferedImage before you can save it.