gpt4 book ai didi

java - 将此指针传递给构造函数的编译器错误?

转载 作者:行者123 更新时间:2023-12-03 20:27:53 25 4
gpt4 key购买 nike

public class MyWindow extends JFrame {

JButton botonCreate = new JButton("Open son windows");

public void doSomething(){
botonCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog vce = new JDialog(this);
}
});
}
}

想法是在子级可见时阻止 JFrame 父级 (JDialog)。

JDialog 的构造函数的参数必须是包含类“MyWindow”,但范围问题是 ActionListener,这会产生以下错误。

我该如何解决这个问题?

错误信息:

no suitable constructor found for JDialog() constructor JDialog(java.awt.Frame) is not applicable (actual argument cannot be converted to java.awt.Frame by method invocation conversion) constructor JDialog(java.awt.Dialog) is not applicable (actual argument cannot be converted to java.awt.Dialog by method invocation conversion)

最佳答案

你的问题很简单。当您使用 this 时,您实际上是在使用 ActionListener.this。因此,要更正此错误,您必须通过使用 MyWindow.this 指定它来向编译器解释您想要实际使用封闭类 this

class MyWindow extends JFrame { 

JButton botonCreate = new JButton("Open son windows");

public void doSomething(){
botonCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialog vce = new JDialog(MyWindow.this);
}
});
}
}

关于java - 将此指针传递给构造函数的编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10567791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com