Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFileChooser not showing up

I have a method that takes a txt file as an input. I used to use string by typing the direct path to the file. But it became burdensome whenever I tried to use different file for an input. I try implementing JFileChooser but with no luck.

This is the code, but nothing happening.

public static JFileChooser choose;
File directory = new File("B:\\");
choose = new JFileChooser(directory);
choose.setVisible(true);        
File openFile = choose.getSelectedFile();

FileReader fR = new FileReader(openFile);
BufferedReader br = new BufferedReader(fR);

2 Answers

As per Java tutorial on How to Use File Choosers:

Bringing up a standard open dialog requires only two lines of code:

//Create a file chooser
final JFileChooser fc = new JFileChooser();
...
//In response to a button click:
int returnVal = fc.showOpenDialog(aComponent);

The argument to the showOpenDialog method specifies the parent component for the dialog. The parent component affects the position of the dialog and the frame that the dialog depends on.

Note as per docs it can also be:

int returnVal = fc.showOpenDialog(null);

If the parent is null, then the dialog depends on no visible window, and it's placed in a look-and-feel-dependent position such as the center of the screen.

  Also have a read on Concurrency in Swing if you haven't already.

like image 191
David Kroukamp Avatar answered Sep 02 '25 18:09

David Kroukamp


No blocking code (as David Kroukamp suggest). It solves "not showing up" problem.

Runnable r = new Runnable() {

@Override
public void run() {
    JFileChooser jfc = new JFileChooser();
    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if( jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ){
        selected = jfc.getSelectedFile();
    }
}
}
SwingUtilities.invokeLater(r);
like image 36
Emerson Moretto Avatar answered Sep 02 '25 19:09

Emerson Moretto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!