首页 > 解决方案 > 当 ButtonListener() 既是父类又是子类时,它是如何工作的?

问题描述

我有一个学校的终极项目,我必须包括本学期学到的尽可能多的元素,其中两个是方法和 gui。在我正在尝试制作的程序中,父类和子类中都有一个 ButtonListener,但是父类中存在错误:nameConfirm.addActionListener(new ButtonListener())这表示 ButtonListener 无法解析为一种类型。我知道这与层次结构有关,但我不知道应该如何解决它。

我有一个模糊的想法,有些人使用“this”或覆盖,但我并不真正了解它们是如何工作的。

这是父类:

public void startGame() {
    JPanel namePanel = new JPanel();
    JButton nameConfirm = new JButton("ask");
    nameConfirm.addActionListener(new ButtonListener());
    namePanel.add(nameConfirm);
    setContentPane(namePanel);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(800, 175);
    setResizable(false);
    setLocationRelativeTo(null);
    class ButtonListener implements ActionListener {
    }
}

这是子类:

public cpt2() {
    JPanel startingPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    newGame = new JButton("New Game");
    newGame.addActionListener(new ButtonListener());
    buttonPanel.add(newGame);
    checkStats = new JButton("Statistics");
    checkStats.addActionListener(new ButtonListener());
    buttonPanel.add(checkStats);
    exit = new JButton("Exit");
    exit.addActionListener(new ButtonListener());
    buttonPanel.add(exit);
    startingPanel.add(buttonPanel);
    setContentPane(startingPanel);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(1110, 375);
    setResizable(false);
    setLocationRelativeTo(null);
public class ButtonListener extends JFrame implements ActionListener{
    public void actionPerformed(ActionEvent a) {
        if (a.getSource() == newGame){
            cptRun.startGame(); 

        }
        else if (a.getSource() == checkStats){

        }
        else if (a.getSource() == exit){
            System.exit(0);
        }
    }
}
}

我希望摆脱错误并为父类和子类中的不同 JPanel 提供工作按钮。

标签: javaswinguser-interfaceawtactionlistener

解决方案


这是父类

那是一个方法,并且你class在一个方法中内联了一个。

更常见的方法是

nameConfirm.addActionListener(new ActionListener() {
    // Implement ActionListener methods here, within anonymous class
});

或者将匿名类移动到变量中

final ActionListener buttonListener = new ActionListener() {
    // Implement ActionListener methods here, within anonymous class
};
nameConfirm.addActionListener(buttonListener);

这是子类

目前尚不清楚这里的课程是什么。你有一个构造函数cpt2public class ButtonListener extends JFrame implements ActionListener

我想你想要的是这个,例如

public class Cpt2Frame extends JFrame implements ActionListener {
    public Cpt2Frame() {
        // some button
        someButton.addActionListener(Cpt2Frame.this); // 'this' class 'is-a' ActionListener
    }

    // Implement ActionListener methods within defined class
}

或者你可以创建一个单独的文件 ButtonListener.java,它不应该是一个 JFrame,只是一个监听器接口

public class ButtonListener implements ActionListener {

}

然后,你可以做addActionListener(new ButtonListener())


推荐阅读