gpt4 book ai didi

Java Swing 按钮监听器不工作

转载 作者:行者123 更新时间:2023-11-29 05:43:35 24 4
gpt4 key购买 nike

我有两个使用 java swing 的游戏板按钮监听器。

最初创建了一个俄罗斯方 block 网格,然后在每个按钮监听器中添加了功能。

我在我的 Play.java 中像这样设置板:

final TetrisGame g = new TetrisGame(11,1);
final BoardGraphics graphics = new BoardGraphics(TetrisBoard.BOARD_WIDTH, 40, g);

然后在同一个 Play.java 中创建按钮监听器:

graphics.btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Action arc = p.getAction(g);
g.update(arc);
graphics.colours.clear();
graphics.setColor(g.getBoard().getGrid());
while (arc instanceof Store){
arc = p.getAction(g);
g.update(arc);
graphics.colours.clear();
graphics.setColor(g.getBoard().getGrid());
}

graphics.tiles.redraw();
System.out.println();
System.out.println(g.toString());
System.out.println();
}

});


graphics.btnAuto.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{

while (!g.gameEnded()){
Action arc = p.getAction(g);
g.update(arc);
graphics.colours.clear();
graphics.setColor(g.getBoard().getGrid());
while (arc instanceof Store){
arc = p.getAction(g);
g.update(arc);
//graphics.colours.clear();
graphics.setColor(g.getBoard().getGrid());
}
graphics.tiles.redraw();
System.out.println();
System.out.println(g.toString());
System.out.println();
/*try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/

}

}

});

btnStart 运行完美,按下一次,根据 AI 代理给出的下一步 Action 绘制俄罗斯方 block 板。

我希望 btnAuto 在用户不按 btnStart 生成移动直到结束的情况下播放每个移动。然而,我的 btnAuto 没有在网格上绘制任何东西,而是游戏的最终状态,即完成状态。

谁能看出为什么这可能不会在 while 循环中生成每个移动后重新绘制网格?

最佳答案

您的 while 循环在 Swing 事件线程上被调用,因此阻止线程执行其必要的操作,包括呈现 GUI 和与用户交互:

while (!g.gameEnded()){
Action arc = p.getAction(g);

// ....

}

我会使用 Swing Timer这里而不是 while (true) 循环。另一种选择是使用后台线程,但由于您想要的只是一个非常简单的游戏循环并且不需要在后台运行一些长时间运行的程序,我认为第二种选择会更复杂并且没有额外的好处。

顺便说一句,我很好奇您是如何进行绘图的,以及您是如何使用 Graphics 对象进行绘图的。您不是在组件上调用 getGraphics() 吗?


编辑您在评论中声明:

I currently have a class with a nested class that extends JPanel. The drawing of the grid and getGraphics() is done within the nested class.The parent class creates the component and sets the layout of the GUI as a whole

不要通过在 GUI 组件上调用 getGraphics() 来获取 Graphics 对象,因为获取的 Graphics 对象不会持久存在。要查看是否如此,只需最小化然后恢复您的应用程序并告诉我执行此操作后您的图形发生了什么。您应该在 JPanel 的 paintComponent 覆盖中完成所有绘图。一种选择是在 BufferedImage 上调用 getGraphics() 并使用它绘制到 BufferedImage,然后在 paintComponent 覆盖中显示 BufferedImage。如果您使用第二种技术,请不要忘记在使用完 BufferedImage 的 Graphics 对象后释放它,以免占用系统资源。

关于Java Swing 按钮监听器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16631563/

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