For Minesweeper the basic interface for the game is a simple grid with squares. In Java we will do this by creating a JPanel with GridLayout. For simplicity sake we will assume that the grid will always be 10x10. These are set in the constructor.
import java.awt.*; import javax.swing.*; public class GameGridGui extends JPanel{ public GameGridGui(){ this.setSize(400,400); this.setLayout(new GridLayout(10,10)); } }
Once the basic layout is taken care of the next thing that needs to be done is build the squares. There are lots of ways to do this but since we need to click on the squares there is no reason why we shouldn't just use an array of JButtons. Create a method called buildButtons and call it from your constructor.
import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JPanel; public class GameGridGui extends JPanel{ private JButton squares[][]; public GameGridGui(){ this.setSize(400,400); this.setLayout(new GridLayout(10,10)); squares = new JButton[10][10]; buildButtons(); } private void buildButtons(){ for(int i=0;i<10;i++){ for(int j=0;j<10;j++){ squares[i][j] = new JButton(); squares[i][j].setSize(400,400); this.add(squares[i][j]); } } } }
If you want to test this out to see what it looks like, just create a quick main method with a JFrame.
public static void main(String[] args) { GameGridGui g = new GameGridGui(); JFrame frame = new JFrame("My Minesweeper"); frame.add(g); frame.setSize(400,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }
And with that you have a basic Minesweeper GUI in Java.
how can i change the array into 6x6
ReplyDeleteGood practice, and something I did not do in this example, is to set the width and height as constants. In my case it would be:
ReplyDeletefinal int WIDTH = 10;
final int HEIGHT = 10;
But you can use any numbers you want. The GridLayout would need to be changed in the constructor, and the two for loops in the buildButtons method. It might also be a good idea to change the size, as 400x400 might be a little too large for just a 6x6 grid. 240x240 might be a better window size.
where is the second part? :)
ReplyDeleteDid you ever find a second part?
DeleteNice Example ... I have also write java code for minesweeper visit Minesweeper Example
ReplyDeleteWell Explained . I have write cod for minesweeper game visit minesweeper game
ReplyDelete