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.