问题
I have a button, clicking on which I want the JFileChooser to pop up. I have tried this
JButton browse= new JButton("Browse");
add(browse);
browse.addActionListener(new ClassBrowse());
public class ClassBrowse implements ActionListener {
public void actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
// return the file path
} catch (Exception ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
}
else {
System.out.println("File access cancelled by user.");
}
}
}
Bhe above gives error The method showOpenDialog(Component) in the type JFileChooser is not applicable for the arguments (ClassName.ClassBrowse)
Also, I want it to return the complete file path. How do I do so ?
回答1:
ActionListener
is not aComponent
, you can't passthis
to the file chooser.- You could look at File#getCanonicalPath to get the full path of the file, but you can't
return
it, asactionPerformed
only returns avoid
(or no return type). You could, however, set some other variable, call another method or even set the text of aJLabel
orJTextField
... for example...
回答2:
You can set a instance variable which holds the file name string in the actionPerformed such as
private String fileName;
.......
your code
.......
public void actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog((Component)e.getSource());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
fileName = file.toString();
} catch (Exception ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
}
else {
System.out.println("File access cancelled by user.");
}
}
回答3:
You can pass the container (It might be a JFrame, JDialog, JApplet or any) your JButton lies in to the
fileChooser.showOpenDialog()
and the filechooser will open as a modal dialog on top of that container.
来源:https://stackoverflow.com/questions/16351875/jfilechooser-on-a-button-click