Getting the Error: Cannot instantiate the type java.awt.event.ActionListener
所以我想做一个井字游戏,我对JFrames,面板,几乎所有的图形用户界面都是全新的。我希望这不被认为是一个重复,因为我扫描这个网站几个小时,试图找到一个答案。很好,因为我是新来的,可能有答案,但我不明白。无论如何,错误都在标题中说明,我的目标是找出如何检测单击了哪个按钮,然后使用if/else语句来控制接下来会发生什么,方法是。我意识到一些导入的内容没有被使用,但是我计划一旦我在程序中得到进一步的应用,它们可能会被使用。再次,我是新来的摇摆和周围的一切。我的大部分知识都是自学的,所以任何帮助都是值得感激的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import java.util.Scanner; import java.lang.Object; import java.awt.Component; import java.awt.Container; import java.awt.Window; import java.awt.Frame; import javax.swing.JFrame; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class ticTacToe implements ActionListener //uses action listener because of the use of buttons, so it needs to know when the buttons are clicked { public static JFrame menuFrame = new JFrame("Tic-Tac-Toe"); public static JPanel board = new JPanel(), menu = new JPanel(); public static JButton instruct = new JButton("Instructions"), pVP = new JButton("Player VS. Player"), pVC = new JButton("Player VS. Computer"); public static void main (String[]args) { menu(); } public static void menu ()//the main menu of the game { menu.setLayout(new FlowLayout());//arranges the layout of the buttons on the panel menu.add(instruct);//adds the instruction button menu.add(pVP);//adds the player vs player button menu.add(pVC);//adds the player vs computer button menuFrame.add(menu);//creates the panel menuFrame.setSize(450, 78); menuFrame.setLocationRelativeTo(null);//sets the location to the centre of the screen menuFrame.setVisible(true);//makes the menu visible } public void actionPerformed(ActionEvent actionEvent) { instruct.addActionListener(new ActionListener()); System.out.println(actionEvent.getActionCommand()); } } |
这是
为了使这有意义,最简单的修复方法是将该行更改为
1 2 3 4 5 6 7 8 9 10 11 12 | public class TicTacToeListener implements ActionListener { public void actionPerformed(ActionEvent e) { // game logic here } } public class ticTacToe implements ActionListener { public void actionPerformed(ActionEvent actionEvent) { instruct.addActionListener(new TickTacToeListener); System.out.println(actionEvent.getActionCommand()); } } |