gpt4 book ai didi

java - 通过为 JButton 着色的俄罗斯方 block GUI。渲染问题

转载 作者:行者123 更新时间:2023-11-29 05:46:55 25 4
gpt4 key购买 nike

我正在制作俄罗斯方 block 游戏,对于我的 GUI,我选择为 JButtons 着色以用作我的俄罗斯方 block 板。我设置了一个 JButton 网格。我计划循环访问从

返回的俄罗斯方 block 网格
newGrid = game.gamePlay(oldGrid);

并根据每个网格元素中的整数为每个 JButton 着色。返回的俄罗斯方 block 网格是一个整数数组,每个数字代表一种颜色。截至目前,我没有用户交互,我只是想拥有基本的 GUI,其中 block 直接下降。

final JPanel card3 = new JPanel();
// Tetris setup
JButton startGame = new JButton("START GAME");
card3.setLayout(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
card3.add(startGame, gbc2);
gbc.gridy = 1;
startGame.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card3.remove(0); //remove start button

Game game = new Game();
int[][] oldGrid = null;
int[][] newGrid = null;
boolean firstTime = true;

JButton[][] grid; // tetris grid of buttons
card3.setLayout(new GridLayout(20, 10));
grid = new JButton[20][10];
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 10; j++) {
grid[i][j] = new JButton();
card3.add(grid[i][j]);
}
}

while (true) {
if (firstTime) {
newGrid = game.gamePlay(null);
} else {
newGrid = game.gamePlay(oldGrid);
}

//Coloring Buttons based on grid

oldGrid = newGrid;
firstTime = false;
card3.revalidate();
}
}
});

这是游戏类的代码

public class Game
{
static Tetris game;

public int[][] gamePlay(int[][] grid) {
if (grid == null) {
game = new Tetris();
System.out.println("first time");
}
else {
game.setGrid(grid);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
game.move_Down();
game.print_Game();

return game.getGrid();
}
}

游戏.print_Game();将网格打印到控制台窗口,以便我可以从文本上看到发生了什么。但是 card3.revalidate();似乎不起作用,因为 GUI 在打印开始时暂停。如果我在 while 循环之前移动 revalidate 然后注释掉 while 循环,GUI 输出:

enter image description here

这就是我想要的。但是为了给按钮涂上某种颜色,我需要在网格变化时在 while 循环中重新验证。

有什么建议吗?

最佳答案

  1. 使用 GridLayout(更简单的 LayoutManager)代替 GridBagLayout

  2. 使用 Swing Timer 而不是 Runnable#Thread

  3. while (true) {是无限循环

  4. Thread.sleep(1000); 可以卡住 Swing GUI 直到 sleep 结束,无限循环 Thread.sleep 会导致不负责任的应用程序

  5. 看不到JButton.setBackground(somecolor)

  6. 使用 KeyBindings(添加到 JButtons 容器)进行旋转

关于java - 通过为 JButton 着色的俄罗斯方 block GUI。渲染问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15533348/

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