java - JFileChooser showOpenDialog 方法不适用于 ActionListener

标签 java eclipse windowbuilder

我一直在尝试遵循此网站上的这些 Java 教程

http://www.homeandlearn.co.uk/java/java.html

但是教程是在 Netbeans 中进行的,而我使用的是 Eclipse。

到目前为止,还没有遇到任何困难。 http://www.homeandlearn.co.uk/java/opening_files.html

在给定的教程中,显示​​了使用 JFileChooser 通过名为“Open”的 JMenuItem 打开文件。但是,当我使用网站中给出的代码时,会发生以下错误

JFileChooser 类型中的方法 showOpenDialog(Component) 不适用于参数 (new ActionListener(){})

这是发生错误的代码。

    JMenuItem mntmNewMenuItem = new JMenuItem("Open");
    mntmNewMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        int returnVal = db.showOpenDialog(this);
        }
    });

所以,我的问题是,我应该在上面的代码 stub 中更改什么才能使用文件选择器?

如果您想查看完整代码,我会根据您的要求将其放入。

最佳答案

错误的含义:方法 showOpenDialog 需要一个 Component 类型的参数,但正在使用 ActionListener 进行调用。更准确地说,给定的参数是实现 ActionListener 的匿名类,而不是 Component:

new ActionListener()  { ... }

在我使用的地方声明的方法内。 。 . 关键字 this 指向该匿名类的实例。

请参阅 showOpenDialog() 的文档,它需要一个父级或 null:

Pops up an "Open File" file chooser dialog. Note that the text that appears in the approve button is determined by the L&F.

Parameters:

parent - the parent component of the dialog, can be null; see showDialog for details

以及showDialog()的相关文档:

The parent argument determines two things: the frame on which the open dialog depends and the component whose position the look and feel should consider when placing the dialog. ... If the parent is null, then the dialog depends on no visible window, and it's placed in a look-and-feel-dependent position such as the center of the screen.

通常传递的参数是JFrameJPanel,它们应该在视觉上包含对话框,但它可以是null:

    int returnVal = db.showOpenDialog(null);

关于java - JFileChooser showOpenDialog 方法不适用于 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43138613/

相关文章:

java - Eclipse,不会导入图像?

java - 更改 void 方法内的变量值以便在 Java 外部使用?

java - 长轮询卡住浏览器并阻止其他 ajax 请求

java - gcm - 是否可以知道消息是否发送到离线设备?

eclipse - 在 BIRT 报告中显示空白而不是 0 或 0.0

java - 为什么当我将嵌套的静态 Fragment 类声明为私有(private)时会产生错误?

java - SWT/WindowBuilder 中的多行按钮文本?

java - 回到之前的 JPanel

java - 如何使用 Google 登录验证我的应用程序?

java - 如何将资源目录而不是单个文件包含到编译类路径中?