2012-09-11 31 views
-2

我是Java中的一个大新手(几乎所有语言)。我正在尝试为任务制作扫雷游戏,而我仍处于测试阶段。然而,我仍然坚持一旦按下按钮,如何将地雷显示为“0”。我创建了Jbuttons使用2d数组,但我似乎不能将“0”放在我想要的特定按钮上。一旦按下Jbutton就设置文本

这是我的代码(请原谅丑陋/可能的低效率)当谈到GUI的时候,我真的无能为力。

import java.awt.*; 
import javax.swing.*; 
import java.awt.GridLayout; 
import java.awt.event.*; 
import java.awt.geom.*; 
import javax.swing.event.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JOptionPane; 
import javax.swing.JFrame; 

public class Grid extends JPanel { 
    // Initializes rows,columns and mines 
    int rows = 10; 
    int cols = 10; 
    int i, j = 0; 
    int mines = 10; 
    boolean[][] setmine = new boolean[rows][cols]; 
    boolean[][] clickable = new boolean[rows][cols]; 
    private JToggleButton squares[][], squares2[][]; 

    // Contructor for creating a grid(with default size 400x400 
    public Grid() { 
     this.setSize(600, 600); 
     this.setLayout(new GridLayout(rows, cols)); 
     squares = new JToggleButton[rows][cols]; 
     buildButtons(); 
    } 

    private void buildButtons() { 
     // loops are used for creating the "buttons" on the grid. 
     int MinesNeeded = 10; 
     // builds buttons 
     // ---------------------------------------- 
     for (i = 0; i < rows; i++) { 
      for (j = 0; j < cols; j++) { 
       squares[i][j] = new JToggleButton(); 
       // squares[i][j].setEnabled(false); 
       squares[i][j].setSize(600, 600); 

       // -------------------------------------------------- 
       // This part randomises the mines 
       // ----------------------------------------------------- 
       while (MinesNeeded > 0) { 

        int x = (int) Math.floor(Math.random() * rows); 
        int y = (int) Math.floor(Math.random() * cols); 
        if (!setmine[x][y]) { 
         setmine[x][y] = true; 

         MinesNeeded--; 
        } 
       } 
       // ---------------------------------------------------------------------------- 

       this.add(squares[i][j]); 

       if (setmine[i][j] == true) { 

        squares[i][j].addActionListener(new ActionListener() { 
         public void actionPerformed(ActionEvent ae) { 
          // this is the problem 
          squares[i][j].setText("0"); 
         } 
        }); 
       } 
      } 
     } 
    } 

    public static void main(String[] args) { 
     Grid g = new Grid(); 
     JFrame frame = new JFrame("Minesweeper"); 

     frame.add(g); 
     frame.setSize(600, 600); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
} 

回答

0

我的建议是在按下时显示一个JLabel不显示一个JButton的数量,而是有你我的电池使用CardttLayout以便它最初将显示一个JButton,但随后。我在stackoverflow上有一个这样的例子,我将搜索并通过链接返回给您。

这里的链接:Minesweeper Action Events

及这里的解释我的一些更详细一点代码的链接:Need help with my minesweeper program?

如果你运行程序,你会看到一个初始画面,如下所示:

MineSweeper1

按空方后,你会看到所有空方格的间隙:

MineSweeper2

击中炸弹后,你会看到所有的炸弹显示:

MineSweeper3

相关问题