JFileChooser not showing

I had a problem with JFileChooser for a long time and could not find help ... The problem is that the file window does not appear. I tried to find the cause of this problem, and I tested the following:

public class Test {
   public static void main (String[] args) {   
   load();     
   }
   public static void load () {
      String folder = System.getProperty("user.dir");
      JFileChooser fc = new JFileChooser(folder);
      int resultat = fc.showOpenDialog(null);  
   }
}

When I run this code, I get a window to display.

But when I try this:

public class Test {
    public static void main (String[] args) {   
    String input = JOptionPane.showInputDialog(null, "Make your choice!\n" +
                                                     "1. load file");      
    load();   

    }
}

the window is not yet displayed, the programming is still running ... I do not know what might cause this problem.

+4
source share
2 answers

Java on a Mac is really picky about Swing things going on in Thread Dispatch Thread. Try it.

import java.awt.EventQueue;
import javax.swing.JFileChooser;

public class Test {
    private static int result;
    public static void main(String[] args) throws Exception {
        EventQueue.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                String folder = System.getProperty("user.dir");
                JFileChooser fc = new JFileChooser(folder);
                result = fc.showOpenDialog(null);
            }
        });
        System.out.println(result);
    }
}

InvokeAndWait . Runnable, Swing, . InvokeLater, .

+5

, JFileChooser , JDialog

JFileChooser fileChooser = new JFileChooser();
JDialog dialog = new JDialog();  

              fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
              int result = fileChooser.showOpenDialog(dialog);
              if (result == JFileChooser.APPROVE_OPTION) {
                  File selectedFile = fileChooser.getSelectedFile();
                  System.out.println("Selected file: " + selectedFile.getAbsolutePath());
              }else{
                  System.out.println("Cancelled");
              }
0

Source: https://habr.com/ru/post/1614963/


All Articles