1

I've been trying to use JFileChooser but I have the problem that the program doesn't stop running, here's my code:

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class copiarArcivos {

    public static void main(String[] args) {
       JFileChooser();
    }

    public static void JFileChooser(){
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        int result = fileChooser.showOpenDialog(new JFrame());
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            System.out.println("Selected file: " + selectedFile.getAbsolutePath());
        }
    }
}

Should I simply put a break at the end of the if?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

Don't create an empty JFrame. You can just use null:

//int result = fileChooser.showOpenDialog(new JFrame());
int result = fileChooser.showOpenDialog(null);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thanks, i thought that you needed one, but it seems i was wrong. –  Oct 06 '17 at 20:12
  • Regarding what the argument is for [JavaDoc](https://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html#showDialog(java.awt.Component,%20java.lang.String)). Used for placing the pop-up relative to its parent. Null places it relevant to the environment. – Compass Oct 06 '17 at 20:24
  • 1
    Warning, when using `null` as the parameter, a new `Frame` will be created which can be disposed with `JOptionPane.getRootFrame().dispose();` when you are done with `JFileChooser`s and `JOptionPane`s. See [here](https://stackoverflow.com/questions/33788138/calling-jfilechooser-twice-in-invokelater-causes-program-not-to-exit) for example. – gthanop Dec 20 '21 at 10:16
1

You have to change the method name of JFileChooser in main method. and also in the declaration of this method. You can use JFileChooser2 instid of JFileChooser on both.

Amit
  • 31
  • 4