Hello as an exercise I am trying to program a minesweeper. I thought that with what I had done, at least the window and all the buttons should be visible, but it's not like that and I don't understand what I'm missing. Every time I compile nothing happens at all. (I leave the loadNumbers() method just in case, but the error shouldn't be there. I clarify because it's cumbersome to read and I don't think it's necessary). The idea is to generate 100 buttons, of which 20 are going to be bombs, and just like in windows minesweeper, each button is going to have a number that indicates how many bombs it has around it (it could be 0 or more).
import javax.swing.*;
public class Recursividad extends JFrame implements ActionListener {
JButton contenedor [] [] = new JButton [10] [10];
Recursividad() {
setLayout (null);
for (int f = 0 ; f < 10 ; f++) {
for(int c = 0; c< 10; c++) {
contenedor [f][c] = new JButton("0");
contenedor [f] [c].setBounds (20 + c * 41, 50 + f * 41, 41, 41);
contenedor [f] [c].setBackground (Color.lightGray);
contenedor [f] [c].setForeground (Color.lightGray);
contenedor [f] [c].addActionListener (this);
add (contenedor [f] [c]);
}
}
cargarBombas();
cargarNumeros();
}
public void cargarBombas() {
for (int x = 0; x < 20; x++) {
int f = 0;
int c = 0;
do {
f = (int) (Math.random() * 10);
c = (int) (Math.random() * 10);
} while (contenedor[f][c].getText() != "b");
contenedor [f] [c].setText("b");
}
}
public void cargarNumeros() {
for(int f = 0; f < 10 ; f++ ) {
for (int c = 0; c < 10 ; c++) {
int contador = 0;
if (contenedor [f][c].getText() != "b") {
if (f -1 >= 0 && c-1 >= 0 && contenedor [f-1][c-1].getText() == "b" )
contador++;
if (c -1 >= 0 && contenedor [f-1][c].getText() == "b")
contador++;
if (f +1 <= 9 && c -1 >= 0 && contenedor [f-1][c].getText() == "b")
contador++;
if (f +1 <= 9 && contenedor [f-1][c].getText() == "b")
contador++;
if (f +1 <= 9 && c+1 <= 9 && contenedor [f+1][c+1].getText() == "b")
contador++;
if (c +1 <= 9 && contenedor [f][c+1].getText() == "b")
contador++;
if (f -1 >= 0 && c+1 <= 9 && contenedor [f-1][c+1].getText() == "b")
contador++;
if (f -1 >= 0 && contenedor [f-1][c].getText() == "b")
contador++;
contenedor [f][c].setText(String.valueOf(contador));
}
}
}
}
public void actionPerformed(ActionEvent e) {
for (int f = 0 ; f < 10 ; f++) {
for (int c = 0 ; c < 10 ; c++) {
if (e.getSource () == contenedor [f] [c])
{
if (contenedor [f] [c].getText ().equals ("b") == true)
{
setTitle ("Boooooooooooooomm");
// desactivarJuego ();
}
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Recursividad p = new Recursividad();
p.setBounds (0, 0, 470, 600);
p.setVisible(true);
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I have corrected your code so that it shows the Jframe -solution: inside the constructor add the setVisible() and setBounds() methods, add a BorderLayout layout to place it in the center and occupy the entire window.
Result