0

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();
            }
        });
    }
}
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274

2 Answers2

5

I usually don't embed the chooser in the top-level Frame or add an action listener, instead I add a button or menu option to the frame to trigger when to show the chooser, then wait for showOpenDialog() to return and then call getSelectedFile().

What I usually do is this:

public class MyJFrame extends javax.swing.JFrame {

    public MyJFrame() {
        JButton btn = new JButton("open file");
        add(btn);
        btn.addActionListener(e -> {
            selectFile();
        });
        pack();
        setVisible(true);
    }

    public void selectFile() {
        JFileChooser chooser = new JFileChooser();
        // optionally set chooser options ...
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File f = chooser.getSelectedFile();
            // read  and/or display the file somehow. ....
        } else {
            // user changed their mind
        }
    }
}
WillShackleford
  • 6,918
  • 2
  • 17
  • 33
0

Well, if you already have the file reference and you are working with Java 1.6 or above, you can use Desktop class:

And you can use the following command to do what you want (of course, your file would be opened with the default application):

Desktop.getDesktop().open(yourSelectedFile);

Remember that "yourSelectedFile" is File type.

Hope it helps and this is what you want to achieve.

Happy coding.

Marcelo Tataje
  • 3,849
  • 1
  • 26
  • 51