【发布时间】:2015-02-28 05:49:56
【问题描述】:
所以我正在尝试制作一款井字游戏,而且我对 JFrame、面板以及几乎所有的 GUI 东西都是全新的。我希望这不被认为是重复的,因为我扫描了这个网站几个小时试图找到答案。很可能是因为我是新手,所以可能有答案,但我不明白。无论如何,标题中说明了错误,我的目标是弄清楚如何检测单击了哪个按钮,然后通过使用方法来使用 if/else 语句来控制接下来会发生什么。我意识到一些导入的内容没有被使用,但我计划一旦我在程序中进一步使用它们可能会被使用。再一次,我是新来的摇摆和它周围的一切。我的大部分知识都是自学的,因此不胜感激。
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());
}
}
【问题讨论】:
标签: java swing awt instance actionlistener