简体   繁体   中英

JFileChooser does not display window in Mac

I have the following code for an application. I used it in Ubuntu and it worked fine. But when I try to run it in macOS with the same java version, it has some problems. The first JFileChooser opens up and works fine. But the second JFileChooser is not displayed.

import javax.swing.*;
import java.io.IOException;

public class App {

    public static void main(String[] args) {
        String segmentedImageDir="", segmentedImageSuffix="", originalImageDir="";
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setDialogTitle("Select Original Images Directory");
        System.out.println("Getting Original Images Directory");
        if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
            originalImageDir = fc.getSelectedFile().getAbsolutePath();
        }
        System.out.println("Original Images Directory: "+originalImageDir);
        fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setDialogTitle("Select Segmented Images Directory");
        System.out.println("Getting Segmented Images Directory");
        //Everything works fine till here
        if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
            segmentedImageDir = fc.getSelectedFile().getAbsolutePath();
        }
        System.out.println("Segmented Images Directory: "+segmentedImageDir);

        segmentedImageSuffix = MainFrame.getSegmentedImageSuffix();

        try{
            new MainFrame(originalImageDir, segmentedImageDir, segmentedImageSuffix);
        } catch (IOException ioe){
            ioe.printStackTrace();
            JOptionPane.showMessageDialog(null, "Could not load image", "IOException", JOptionPane.ERROR_MESSAGE);
        }
    }
}

Yes, this seems to be some buggy weirdness on macs. However, I found an easy fix for you:

There is no actual need to make another instance of JFileChooser here; you can simply delete this line:

fc = new JFileChooser();

and leave everything else, and now it'll pop up the file chooser dialog in directory mode twice, properly titled, just as you want.

This bug report seems to indicate, even though that was not reproducible according to someone at oracle, that this bug has been in there for a while.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM