I have a JFileChooser that is created as shown:
JFileChooser chooser = new JFileChooser();
int choosen = chooser.showOpenDialog(fileSelector.this);
if (choosen == JFileChooser.CANCEL_OPTION) {
System.out.println("Closed");
}
If I close the window with out making a selection I get the error:
Exception in thread "main" java.lang.NullPointerException
at fileSelector.fileSelector(fileSelector.java:32)
at createAndControl.main(createAndControl.java:15)
I wanted to know what the proper way to handle this was, what action should I call on window closed to avoid this?
TIA
It's recommended to do it the other way round:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("Opening: " + file.getName() + ".\n");
} else {
System.out.println("Open command cancelled by user.\n");
}
}
});
}
Related
I want to get the full path of the file that the user saved in Java.
Here is the code of the method save and it works okay but actually i need to get the path that the user had save his file in. Could someone help me:
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class FileChooserSave {
private static void createAndShowUI() {
final JFileChooser chooser = new JFileChooser(new File(".")) {
public void approveSelection() {
if (getSelectedFile().exists()) {
int n = JOptionPane.showConfirmDialog(this, "Do You Want to Overwrite File?", "Confirm Overwrite",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION)
super.approveSelection();
} else
super.approveSelection();
}
};
chooser.setSelectedFile(new File(""));
int returnVal = chooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println(chooser.getSelectedFile());
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Here is a sample of java code for absolute path from JFileChoose
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
hope it helps...
You can get the Absolute path using this method:
myFileChooser.getSelectedFile().getAbsolutePath()
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.
I am using JFileChooser to browse and load a file.
File chooser is loading properly and /i was able to select the file and load as well.
The issue is soon after opening the JFilechooser, the background window of the application goes in to Busy/Not Responding state. And if I Drag the
file chooser window, the background is not drawing properly. It causes the application into the crash state. Any idea why it happens.
Please find my below code
LoadFileButton.addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(filterWithoutExtension);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File selectedFile = null;
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
//Do My Stuff
}
}
});
Please find my FileFilter
FileFilter filterWithoutExtension = new FileFilter() {
#Override
public boolean accept(File f) {
return !f.getName().contains(".");
}
#Override
public String getDescription() {
return "My Description";
}
};
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();
}
}
I disable the new Folder button using the following code:
public void disableNewFolderButton( Container c ) {
System.out.print("in disable fn");
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton)comp;
Icon icon = b.getIcon();
if (icon != null
&& icon == UIManager.getIcon("FileChooser.newFolderIcon"))
{
System.out.print("in disable fn");
b.setEnabled(false);
}
}
else if (comp instanceof Container) {
disableNewFolderButton((Container)comp);
}
}
}
The code is called in the following lines:
JFileChooser of=new JFileChooser();
of.setAcceptAllFileFilterUsed(false);
of.addChoosableFileFilter(new MyFilter());
disableNewFolderButton(of);
But the new folder button is disabled only when the file chooser is first displayed. Suppose i go to some drive , say g: , then the button is enabled again. How to set this right?
this is working for me...
//Create a file chooser
UIManager.put("FileChooser.readOnly", Boolean.TRUE);
JFileChooser fc = new JFileChooser();
Disable the "new folder" Action (which in turn will disable the button):
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class FileChooserAction
{
public static void createAndShowUI()
{
JFileChooser chooser = new JFileChooser();
BasicFileChooserUI ui = (BasicFileChooserUI)chooser.getUI();
Action folder = ui.getNewFolderAction();
folder.setEnabled(false);
chooser.showSaveDialog(null);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
1) It is a bit stupid, but you can keep disabling it in an another Thread. Until the file chooser got invisible.
2) Does hiding the button work? b.setVisible(false);