Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFileChooser from a command line program and popping up Underneath all windows

Ive implemented the jFileChooser in my command line program and it works, just as it should with only one annoying issue. It seems that it opens underneath every window with no alert of any kind. In fact I even missed it a couple of times at first leading me to believe that i had implemented it wrong.

I have implemented this as follows:

System.out.println("Please select the file");
JFileChooser fc = new JFileChooser();
int retValue = fc.showOpenDialog(new JPanel());
if(retValue == JFileChooser.APPROVE_OPTION){
    g.inputFile = fc.getSelectedFile();
}else {
    System.out.println("Next time select a file.");
    System.exit(1);
}

Essentially I only want the jFileChooser in order to have the user select a file as an input file. This is the only component that has a need for a GUI implementation, so if i can avoid writing up an GUI, that would be helpful.

like image 351
kyle phill Avatar asked Sep 21 '11 04:09

kyle phill


People also ask

What is the purpose of JFileChooser?

Class JFileChooser. JFileChooser provides a simple mechanism for the user to choose a file. For information about using JFileChooser , see How to Use File Choosers, a section in The Java Tutorial.

How do I select multiple files in JFileChooser?

JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.


1 Answers

So after trying a variety of things from different stack overflow topics I ended up with a result that consistently and reliably opens above every window on Windows 7.

public class ChooseFile {
    private JFrame frame;
    public ChooseFile() {
        frame = new JFrame();

        frame.setVisible(true);
        BringToFront();
    }
    public File getFile() {
        JFileChooser fc = new JFileChooser();
        if(JFileChooser.APPROVE_OPTION == fc.showOpenDialog(null)){
            frame.setVisible(false);
            return fc.getSelectedFile();
        }else {
            System.out.println("Next time select a file.");
            System.exit(1);
        }
        return null;
    }

    private void BringToFront() {                  
                    frame.setExtendedState(JFrame.ICONIFIED);
            frame.setExtendedState(JFrame.NORMAL);

    }

}

As it stands in my program it is an inner class and is invoked by calling:

System.out.println("Please select the file");
g.inputFile = g.new ChooseFile().getFile();
like image 64
kyle phill Avatar answered Nov 01 '22 23:11

kyle phill