Reputation: 6753
I want to make a button in Java
such that when user clicks it a box opens that allows the user to select a file. Note: For my application , I only need the file path. I do not need the exact file. Is there a way to do this in Java using swing
etc
Upvotes: 1
Views: 4638
Reputation: 1
'private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
// What to do with the file, e.g. display it in a TextArea
textarea.read( new FileReader( file.getAbsolutePath() ), null );
} catch (IOException ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}'
Upvotes: 0
Reputation: 8101
Use JFileChooser
. Write following code inside your actionPerformed
for the Button.
JFileChooser jfc = new JFileChooser();
jfc.showDialog(null,"Please Select the File");
jfc.setVisible(true);
File filename = jfc.getSelectedFile();
System.out.println("File name "+filename.getName());
Upvotes: 4