Here is my jFileChooser swing code which opens another window after clicking the open button. Then we need to select the corresponding file in the second window in-order to actually open that file. I need to to do all the operations on the first window itself.
import com.opencsv.CSVReader;
import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
/*
* Created by JFormDesigner on Tue Sep 22 13:24:36 IST 2015
*/
/**
* @author Avinash Raj
*/
public class FileChooser extends JFrame {
private JFileChooser fileChooser1;
public FileChooser() {
initComponents();
}
private void fileChooser1ActionPerformed(ActionEvent e) {
int returnVal = fileChooser1.showOpenDialog(FileChooser.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
//File file = fc.getSelectedFile();
setVisible(false);
String path=fileChooser1.getSelectedFile().getAbsolutePath();
String filename=fileChooser1.getSelectedFile().getName();
//This is where a real application would open the file.
System.out.println("Opening: " + path + "\n");
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(path), ',', '\'', 1);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String [] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
int no_cols = nextLine.length;
System.out.println(nextLine[0] + nextLine[1] + nextLine[2] );
}
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
setVisible(false);
System.out.println("Open command cancelled by user." + "\n");
}
}
private void initComponents() {
fileChooser1 = new JFileChooser();
setLayout(new BorderLayout());
setSize(700,500);
fileChooser1.addActionListener(e -> fileChooser1ActionPerformed(e));
fileChooser1.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"csv files only", "csv");
fileChooser1.setFileFilter(filter);
add(fileChooser1, BorderLayout.CENTER);
setVisible(true);
setLocationRelativeTo(getOwner());
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
FileChooser f = new FileChooser();
}
});
}
}