Java 俄罗斯方块图形用户界面的颜色JButtons。渲染问题
我正在做一个俄罗斯方块游戏,为了我的图形用户界面,我选择了给JButtons上色,作为我的俄罗斯方块板。我设置了一个JButton网格。我计划循环遍历从中返回的俄罗斯方块网格Java 俄罗斯方块图形用户界面的颜色JButtons。渲染问题,java,swing,user-interface,jbutton,tetris,Java,Swing,User Interface,Jbutton,Tetris,我正在做一个俄罗斯方块游戏,为了我的图形用户界面,我选择了给JButtons上色,作为我的俄罗斯方块板。我设置了一个JButton网格。我计划循环遍历从中返回的俄罗斯方块网格 newGrid = game.gamePlay(oldGrid); 并根据每个网格元素中的整数为每个JButton着色。返回的俄罗斯方块网格是一个整数数组,每个数字代表一种颜色。到目前为止,我还没有用户交互,我只是尝试使用基本的GUI,块直接向下放置 final JPanel card3 = new JPanel();
newGrid = game.gamePlay(oldGrid);
并根据每个网格元素中的整数为每个JButton着色。返回的俄罗斯方块网格是一个整数数组,每个数字代表一种颜色。到目前为止,我还没有用户交互,我只是尝试使用基本的GUI,块直接向下放置
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();
}
}
});
游戏。打印游戏();将网格打印到控制台窗口,以便我可以通过文本查看正在进行的操作。但是,card3.revalidate();似乎不起作用,因为打印开始时GUI暂停。如果我将重新验证日期移到while循环之前,然后注释掉while循环,GUI将输出:
这就是我想要的。但是为了给按钮涂上某种颜色,我需要随着网格的变化在while循环中重新验证
有什么建议吗
GridBagLayout
(更简单的LayoutManager
)而不是GridBagLayout
Swing Timer
而不是Runnable#Thread
while(true){
是无止境的循环Thread.sleep(1000);
可以冻结Swing GUI直到睡眠结束,使用Thread.sleep的无休止循环会导致应用程序无响应
JButton.setBackground(somecolor)
JButtons容器
)进行旋转我可以问一下…你为什么要使用JButtons?使用javax.swing.Timer而不是while loop我实际上决定使用JTable…老实说,我不知道我在想什么。我决定使用JTable。出于某种原因,因为俄罗斯方块通常有3D外观块,我认为使用按钮会有类似的效果。我知道无限循环是在那里,我只是想看看我是否能把这些碎片放到合适的位置。
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();
}
}