【发布时间】:2019-05-25 01:15:43
【问题描述】:
我有一个学校的终极项目,我必须包含我本学期学到的尽可能多的元素,其中 2 个是方法和 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 提供工作按钮。
【问题讨论】:
-
哪行代码导致错误?
-
nameConfirm.addActionListener(new ButtonListener());
-
这是How to Write an Action Listener 上 Oracle 的 Java 教程主题的链接。您可能还想用类似的查询搜索网络 (Google) 以找到更多示例。
标签: java swing user-interface awt actionlistener