gpt4 book ai didi

java - Tic Tac Toe Java GUI 设置游戏 field

转载 作者:行者123 更新时间:2023-12-01 21:11:30 25 4
gpt4 key购买 nike

我目前正在用 Java GUI 编写简单版本的 Tic Tac Toe。我在设置比赛 field 时遇到问题。按钮代表一个方 block ,玩家可以按下该方 block 来获得“X”或“O”。

 //Playing field class

import java.awt.*;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
class TicTacToeFrame extends JFrame {
private JFrame game = new JFrame("Tic Tac Toe");
private JPanel pane1, pane2, pane3;
Button button = new Button();
public TicTacToeFrame() {
game.setSize(300, 300);
game.setVisible(true);
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pane1 = new JPanel();
pane2 = new JPanel();
pane3 = new JPanel();

add(pane1, BorderLayout.NORTH);
add(pane2, BorderLayout.CENTER);
add(pane3, BorderLayout.SOUTH);

pane1.setBackground(Color.white);
pane2.setBackground(Color.white);
pane3.setBackground(Color.white);

placeButton();
}
public void placeButton() {
for (int i = 1; i < 10; i++) {
if (i < 4) {
pane1.add(button.getButton());
}
else if (3 < i && i < 7) {
pane2.add(button.getButton());
}
else if (6 < i && i < 10) {
pane3.add(button.getButton());
}
}
}
}

//Button class

import javax.swing.JButton;
import java.awt.event.ActionListener;
public class Button {
private JButton button;
private int number = 0;
private String player;
public Button() {
button = new JButton();
}
public String getPlayer() {
return player;
}
public JButton getButton() {
return button;
}
public void changePlayer() {
for (int i = 1; i < 10; i++) {
if (number % 2 == 0) {
player = "X";
}
else {
player = "O";
}
number++;
}
}
}

当我在主程序中运行程序时,我收到了框架,但是,没有放置应该代表正方形的按钮。帮忙?

最佳答案

为什么要将 JFrame(游戏)包装在已经扩展 JFrame 的类中?

我会这样做:

public TicTacToeFrame() {
super("Tic Tac Toe");
//I prefer to call pack() method in this case..
//setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pane1 = new JPanel();
pane2 = new JPanel();
pane3 = new JPanel();

add(pane1, BorderLayout.NORTH);
add(pane2, BorderLayout.CENTER);
add(pane3, BorderLayout.SOUTH);

pane1.setBackground(Color.white);
pane2.setBackground(Color.white);
pane3.setBackground(Color.white);

placeButton();
//call setVisible after you added all the buttons
setVisible(true);
pack();
}

placeButton 方法中也存在一个错误(正如 Hovercraft Full Of Eels 所注意到的):

public void placeButton() {
for (int i = 1; i < 10; i++) {
//You should create the button all the time
Button button = new Button();
if (i < 4) {
pane1.add(button.getButton());
}
else if (3 < i && i < 7) {
pane2.add(button.getButton());
}
else if (6 < i && i < 10) {
pane3.add(button.getButton());
}
}
}

关于java - Tic Tac Toe Java GUI 设置游戏 field ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com