I had to make a minefield game for my java class, in which a user must click 10 squares without hitting the mine. I was able to make it so when the mine is clicked, all the other squares change their color and the game ends. However, i need to add a congratulatory message in the NORTH JFrame region when the user clicks 10 squares successfully. How would i go about doing this? I added an if statement for this,
however it doesnt seem to be working, so i'm assuming i did it wrong.
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Minefield extends JFrame implements ActionListener { JPanel[] aPanel = new JPanel[20]; JButton[] aButton = new JButton[20]; int bomb = (int) (Math.random() * 100) % 20; int counter; JLabel bLab = new JLabel(""); public Minefield() { setTitle("Mine Field"); setSize(500, 500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(5, 5)); for (int i = 0; i<aPanel.length; i++) { aPanel[i] = new JPanel(new GridLayout(1, 1)); aButton[i] = new JButton(""); aButton[i].setBackground(Color.BLUE); add(aPanel[i]); aPanel[i].add(aButton[i]); aButton[i].addActionListener(this); }//end forloop } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); counter++; for (int i = 0; i<aButton.length; i++) { if(aButton[i] == source) { if(i == bomb) { aButton[i].setBackground(Color.RED); for (int a = 0; i<aButton.length; a++) { if(a != bomb) { aButton[a].setBackground(Color.WHITE); } } } else { aButton[i].setBackground(Color.WHITE); if(counter == 10) { bLab.setText("You win!"); } } } }//end forloop } public static void main(String[] args) { Minefield b1 = new Minefield(); } }