-1
我正在尝试创建一个Tic Tac Toe游戏,它有一个菜单,允许您选择想玩哪个游戏版本,但是在经过几个小时的研究并尝试不同的事情后,我无法弄清楚如何去做它。我将如何从一个已经运行的单独的类运行一个类?
package TicTacToeGame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToeMenu extends TicTacToe2
{
private JButton b1;
private JButton b2;
public TicTacToeMenu()
{
b1 = new JButton("Regular");
b2 = new JButton("Colour");
JTextField display = new JTextField();
display.setEditable(false);
display.setText("Welcome to TicTacToe! Choose the version you would like to play!");
JPanel grid = new JPanel();
grid.setLayout(new GridLayout(1,2));
grid.add(b1);
grid.add(b2);
setLayout(new BorderLayout());
add(display,BorderLayout.NORTH);
add(grid,BorderLayout.CENTER);
b1.addActionListener(new ButtonResponse());
b2.addActionListener(new ButtonResponse());
}
public static void main(String[]args)
{
TicTacToeMenu frame = new TicTacToeMenu(); //create the custom frame
frame.setSize(500,500); //set the frame size
frame.setLocationRelativeTo(null); //center on screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make close button work
frame.setVisible(true); //make frame display
}
class ButtonResponse implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("action detected");
if(e.getSource() == b1)
{
}
else if(e.getSource() == b2)
{
}
else
{
}
}
}
}
我希望它运行井字的第一个版本(类是公共类井字游戏)时,点击,它的版本2(公共类井字游戏)单击B2时,按钮B1。
对于初学者来说,你的菜单类绝对不应该延伸你的游戏(TicTacToe2)类。这是滥用继承,并可能导致重大的代码问题,所以我建议你将它们分开。 –
接下来,我建议您尝试在ActionListener的if块中添加一些代码。我们不知道你在哪里可能会被卡住,而没有看到至少有人试图做某件事。另外,你的游戏课程扩展了什么? JFrame(可能不是一个好主意)? JPanel(更好)?没有或没有(这可以工作,也很好)?请告诉我们并向我们展示更多关于这些类的内容。 –