gpt4 book ai didi

java - 使用内部类(java)时遇到问题

转载 作者:行者123 更新时间:2023-12-02 09:43:42 29 4
gpt4 key购买 nike

我正在尝试使用内部类设置,但是遇到了一些问题。这是我尝试使用的代码:

public class GUI
{
class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// do something
}
}

private static void someMethod()
{
JButton button = new JButton( "Foo" );
button.addActionListener(new ButtonHandler());
}
}

这是我收到的错误消息(在 Eclipse 中):

No enclosing instance of type GUI is accessible. Must qualify the allocation with an enclosing instance of type GUI (e.g. x.new A() where x is an 
instance of GUI).

请问有人可以帮我吗?

最佳答案

更改声明:

class ButtonHandler implements ActionListener

致:

static class ButtonHandler implements ActionListener

如果没有“static”修饰符,它是一个实例级内部类,这意味着您需要一个封闭的 GUI 类的实例才能工作。如果将其设为“静态”内部类,则它充当普通的顶级类(隐式静态)。

(在您的示例中这是必要的关键原因是 someMethod 是静态的,因此您在该上下文中没有封闭类的实例。)

关于java - 使用内部类(java)时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841210/

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