gpt4 book ai didi

java - 无法从内部 Action 到达现场

转载 作者:行者123 更新时间:2023-12-02 01:32:56 25 4
gpt4 key购买 nike

public class GameMenu extends JPanel{

private final Core core;
private final JButton loadGame;
private final JButton saveGame;
private final JButton exit;
private final JButton newGame;

public GameMenu(Core core){
setPreferredSize(new Dimension(600, 600));
setBackground(Color.BLACK);
this.core = core;

newGame = new JButton(newGameAction);
loadGame = new JButton(loadGameAction);
saveGame = new JButton(saveGameAction);
exit = new JButton(exitGameAction);


add(newGame);
add(loadGame);
add(saveGame);
add(exit);
}


private Action newGameAction = new AbstractAction("New Game") {
@Override
public void actionPerformed(ActionEvent e) {
this.core.
}
};

嗨,我想调用一个核心方法而不是调用这个类的方法,这个方法会调用核心的正确方法问题是我不知道如何到达核心领域,因为它找不到谢谢

最佳答案

在这种情况下:

private Action newGameAction = new AbstractAction("New Game") {
@Override
public void actionPerformed(ActionEvent e) {
this.core. // compiling error here: 'core' is not a member of the anonymous inner class
}
};

关键字this 指的是anonymous创建新的 Action 实例(当前对象)时生成的内部类。这个事实在这里解释:Using the this Keyword :

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

由于匿名内部类没有名为core 的成员,因此会出现编译错误。为了解决此问题,请查看此主题:Keyword for the outer class from an anonymous inner class? .

出于实际目的,您应该将上面的行替换为引用您的 GameMenu 类:

private Action newGameAction = new AbstractAction("New Game") {
@Override
public void actionPerformed(ActionEvent e) {
GameMenu.this.core.
}
};

或者您可以删除 this 关键字,编译器将为您解决同样的问题:

private Action newGameAction = new AbstractAction("New Game") {
@Override
public void actionPerformed(ActionEvent e) {
core. // should be recognised as outer class member
}
};

鉴于匿名内部类没有核心成员,编译器将查找外部类(或最终层次结构树,具有适当的可见性)并检查是否有这样的成员,这确实如此。

关于java - 无法从内部 Action 到达现场,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27272405/

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