java中repaint()方法的问题
我不熟悉Java,尝试使用Swing制作一个简单的玩家对电脑的“Tic-Tac-Toe”游戏。在代码中,我使用java中repaint()方法的问题,java,swing,tic-tac-toe,Java,Swing,Tic Tac Toe,我不熟悉Java,尝试使用Swing制作一个简单的玩家对电脑的“Tic-Tac-Toe”游戏。在代码中,我使用paintComponent()方法绘制某些组件,并在播放器或计算机播放后调用repaint()方法。问题是,在我第三次(有时是第二次)点击鼠标后,游戏就冻结了。在gamewindowclass中,我创建了Map类的实例 public class GameWindow extends JFrame{ private final int sizeX = 3; privat
paintComponent()
方法绘制某些组件,并在播放器或计算机播放后调用repaint()
方法。问题是,在我第三次(有时是第二次)点击鼠标后,游戏就冻结了。在gamewindowclass
中,我创建了Map
类的实例
public class GameWindow extends JFrame{
private final int sizeX = 3;
private final int sizeY = 3;
public GameWindow(){
setLocation(400,150);
setSize(406, 452);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
Map map = new Map(sizeX, sizeY);
add(map, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(1, 2));
add(bottomPanel, BorderLayout.SOUTH);
Button newGame = new Button("Новая игра");
newGame.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Начинаем новую игру");
}
});
Button exit = new Button("Выход");
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
bottomPanel.add(newGame);
bottomPanel.add(exit);
setVisible(true);
}
}
下面是在Map
类中单击鼠标的侦听器:
public class Map extends JPanel {
private final int sizeX;
private final int sizeY;
private int cellWidth;
private int cellHeight;
private int cellX = -1;
private int cellY = -1;
private String lastPlayer = "nobody";
private String[][] table = new String[3][3];
public Map(int sizeX, int sizeY) {
this.sizeX = sizeX;
this.sizeY = sizeY;
setBackground(Color.WHITE);
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
table[i][j] = "empty";
}
}
addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
cellX = e.getX() / cellWidth;
cellY = e.getY() / cellHeight;
if (!winOrDraw()) {
boolean playerProgress = playerProgress();
if(playerProgress) {
botProgress();
}
}
}
});
}
您正在将Swing组件直接添加到JFrame AWT容器中。你不应该那样做。相反,您应该这样做:
JPanel panel = new JPanel();
myFrame.setContentPane(panel);
panel.setLayout(...)
panel.add(...);
panel.validate();
这将解决您的问题。您正在将Swing组件直接添加到JFrame AWT容器中。你不应该那样做。相反,您应该这样做:
JPanel panel = new JPanel();
myFrame.setContentPane(panel);
panel.setLayout(...)
panel.add(...);
panel.validate();
这将解决您的问题。共享winOrDraw()和botProgress()methods@AndriiBugai我已经编辑了我的问题并添加了这些方法。为了更好地帮助您尽快发布正确的帖子,我们需要知道
paintComponent()
问题是,游戏冻结了
——所以请查看您的循环代码。每当我看到while/do循环时,我都会怀疑您的结束条件并不像您期望的那样工作。因此,在循环中添加一些调试语句,以显示最终条件变量的值。另外,不要使用AWT组件的按钮。在Swing应用程序中,您应该使用JButton
。共享winOrDraw()和botProgress()methods@AndriiBugai我已经编辑了我的问题并添加了这些方法。为了更好地帮助您尽快发布正确的帖子,我们需要知道paintComponent()
问题是,游戏冻结了
——所以请查看您的循环代码。每当我看到while/do循环时,我都会怀疑您的结束条件并不像您期望的那样工作。因此,在循环中添加一些调试语句,以显示最终条件变量的值。另外,不要使用AWT组件的按钮。在Swing应用程序中,您应该使用JButton
。