2013-03-20 108 views
1

我正在制作俄罗斯方块游戏和我的GUI,我选择将JButtons作为我的俄罗斯方块板。我建立了一个JButtons的网格。我通过被从俄罗斯方块GUI通过着色JButtons。渲染问题

newGrid = game.gamePlay(oldGrid); 

返回并基于在每个格栅元素的整数颜色的每个的JButton的方块网格计划循环。返回的Tetris网格是一个整数数组,每个数字代表一种颜色。到目前为止,我没有用户交互,我只是想让基本的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(); 
     } 
    } 
}); 

这里是从游戏类

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(); 
    } 
} 

的game.print_Game()的代码;将网格打印到控制台窗口,以便我可以看到文本上发生了什么。但是card3.revalidate();似乎没有工作,因为GUI在打印开始时暂停。如果我while循环之前移动重新验证,然后注释掉while循环,图形用户界面输出:

enter image description here

这就是我想要的。但为了给按钮着色某种颜色,我需要在网格更改时在while循环中进行重新验证。

有什么建议吗?

+2

可我只是问... *为什么*您使用Jbutton将? – Sinkingpoint 2013-03-20 19:54:08

+0

使用javax.swing.Timer而不是while循环 – MadProgrammer 2013-03-20 19:57:18

+0

我实际上决定使用JTable ...我不知道我在说什么是诚实的。 – mstep91 2013-03-21 00:55:13

回答

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

  2. 使用Swing Timer代替Runnable#Thread

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

  4. Thread.sleep(1000);可以冻结的Swing GUI,直到睡眠结束,无限循环与Thread.sleep可能会导致unrespo nsible应用

  5. 不能看到有JButton.setBackground(somecolor)

  6. 使用键绑定(添加到到JButtons container)的旋转

+0

我决定使用一个JTable。由于某些原因,因为俄罗斯方块通常有3D看块,我认为使用按钮会有类似的效果。我知道无限循环在那里,我只是想看看我是否可以让这些东西落到原地。 – mstep91 2013-03-21 00:56:34