我目前正在尝试从Netbeans Platform API使用FileChooserBuilder。以下代码完成了netbeans模块的动作。运行时,它不会显示在窗口/屏幕的中心,而是显示在屏幕左下角的某处。是否有可能使该对话框显示在屏幕中间?

public final class LoadProjectAction implements ActionListener {

    public void actionPerformed(ActionEvent e) {

        File home = new File(
            System.getProperty("user.home")
            + File.separator + "lib");

        FileChooserBuilder fileChooserBuilder = new FileChooserBuilder(
            LoadProjectAction.class);
        fileChooserBuilder.setTitle("Load project");
        fileChooserBuilder.setDefaultWorkingDirectory(home);
        fileChooserBuilder.setApproveText("Load");
        fileChooserBuilder.setDirectoriesOnly(true);


        File directory = fileChooserBuilder.showOpenDialog();

        if (directory != null) {
            return; // nothing to do
        }

        // do some processing here
    }

}


感谢您的想法。

最佳答案

找到了解决方案:

您必须获取JFileChooser实例并在其showOpenDialog方法中设置正确的父组件(然后将其相对于应用程序的主窗口放置)。但是,由于NetBeans尝试在线程上安全地工作-它仅允许一个线程访问组件,因此必须使用EventQueue.invokeLater。

public final class LoadProjectAction implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                // output window
                InputOutput io = IOProvider.getDefault().getIO("File search", true);
                io.select();

                // start in user home directory
                File initialDirectory = new File(
                    System.getProperty("user.home")
                    + File.separator + "lib");

                FileChooserBuilder fileChooserBuilder = new FileChooserBuilder(
                    "LoadProjectAction");
                fileChooserBuilder.setTitle("Load project");
                fileChooserBuilder.setDefaultWorkingDirectory(initialDirectory);
                fileChooserBuilder.setApproveText("Load");
                fileChooserBuilder.setDirectoriesOnly(true);

                JFileChooser jfc = fileChooserBuilder.createFileChooser();
                int value = jfc.showOpenDialog(WindowManager.getDefault().getMainWindow());

                if (value != JFileChooser.APPROVE_OPTION) {
                    return; // nothing to do
                }

                // process selection
            }
        });

    }
}

关于java - FileChooserBuilder未显示在屏幕中央,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5596089/

10-12 14:47