Using a JFileChooser to get absolute path of a file
Hi Guys,
I am developing a program for data analysis. I am using Netbeans to develop a simple Desktop Application. I want to be able to make a JButton which opens a JFileChooser. I then want to be able to use the absolute path of the chosen file in another method which reads the data file.
So to clarify things I have a class ReadData with a method called readFile(String filename), The filename is a string of the absolute path to the file.
I have another class which is storing all the Graphical user interface components (JFrame, JPanel, JMenu). Now somehow I want to learn how to add a button to the GUI class which opens a file chooser popup box and the selected file path is passed on to the other method readFile(String filename) on class ReadData.
I know how to make the button open a file chooser but I don't know how to add this button to the Graphical User Interface and I do not know how to use the result from the ActionListener . Below is some of the code that I have generated. I kind of understand how things work on their own but I don't know how to put them together. Any help is greatly appreciated as ever. :)
Where would I create this button: In the ReadData Class and than add it to the GUI class or in the Gui Class and than use it's result in the ReadData Class?
Code:
//declare new button
static JButton button1 = new javax.swing.JButton();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
int returnName = chooser.showOpenDialog(null);
String path;
if (returnName == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
if (f != null) { // Make sure the user didn't choose a directory.
path = f.getAbsolutePath();//get the absolute path to selected file
//below line to test the file chooser
//System.out.println(path);
}
}
}
public void main(){
// System.out.println(getFilePath());
button1.setAction(null);
button1.setName("Choose File");
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
}