JFrame 中的 JFileChooser 使 setVisible() 冻结

JFileChooser inside a JFrame makes setVisible() freeze

我有一项任务是将 JFileChooser 显示为 JFrame 的一部分。所以将其显示为对话框已经过时了。

我正在使用最基本的方法将它作为一个组件添加到一个不可见的框架中,然后 setVisible() 调用冻结而不是显示框架。

最让我恼火的是,十分之一的框架与 FileChooser 一起出现就很好。这让我觉得这是一个并发问题。

这是仍然存在问题的最小源代码。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

class ApplicationFrame extends JFrame {
  JFileChooser fileChooser;

  public ApplicationFrame(String frameName) {
    super(frameName);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());

    fileChooser = new JFileChooser();
    fileChooser.setControlButtonsAreShown(false);
    panel.add(fileChooser, BorderLayout.CENTER);

    getContentPane().add(panel);
  }
}

public class lab7{
  public static void main(String args[])
  {
    ApplicationFrame windowForApplication = new ApplicationFrame("lab7");
    windowForApplication.setSize(600,600);
    windowForApplication.setVisible(true);
  }
}

如果在最后一个 setVisible 之后放置一个 println,它不会被调用。

如果您注释掉 panel.add(),框架显示得很好。

我还应该如何显示文件选择器?

What irks me the most is that one time out of ten the frame appears with the FileChooser just fine.

所有 Swing 组件都应该在事件调度线程上创建。所以 GUI 创建代码应该包含在 SwingUtilities.invokeLater(...) 中。

阅读有关 Concurrency 的 Swing 教程部分,了解更多信息和如何完成此操作的示例。

你的代码(原样)对我来说没有问题。我在 Windows 7 上使用 JDK7,所以它可能是 version/platform 问题。再次确保代码在 EDT 上执行。

此外,class 名称 ("lab7") 应以大写字符开头。这是否是 SSCCE 并不重要,请保持一致。