我一直在尝试遵循此网站上的这些 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.
通常传递的参数是JFrame
或JPanel
,它们应该在视觉上包含对话框,但它可以是null
:
int returnVal = db.showOpenDialog(null);
关于java - JFileChooser showOpenDialog 方法不适用于 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43138613/