Peaq Peaq - 6 days ago 5
Java Question

Simple Button Array doesn't work

I need to create a simple Minesweeper Game at school. I want to make a JButton-Array for an easy use. However it doesn't work! I fell like i've searched the whole internet for a solution! Can you help me maybe? Here's the code:

public class Minesweeper extends Applet {

public void init() {

//Frameinitialiing

JFrame frame = new JFrame("Minesweeper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int width = 800;
frame.setSize(width, width);
frame.setResizable(false);
frame.setLocation(0,0);
frame.setVisible(true);


//Game

JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);


//Buttons

int w = 80;

JButton[][] button = new JButton[10][10];
for (int i = 1; i == 9 ; i++ ) {

for (int j = 1; j == 9 ; j++ ) {

button[i][j].setBounds(i*80 , j*80 , w , w);
this.add(button[i][j]);

}
}
}
}

Answer

Your code has lots of places that needs to be changed. But I have changed them for you:

    JFrame frame = new JFrame("Minesweeper");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    int width = 800;
    frame.setSize(width, width);
    frame.setResizable(false);
    frame.setLocation(0,0);
    frame.setVisible(true);

    int w = 80;

    JButton[][] button = new JButton[10][10];
    for (int i = 0; i < 10 ; i++ ) {

        for (int j = 0; j < 10 ; j++ ) {
            button[i][j]  = new JButton();
            button[i][j].setBounds(i*80 , j*80 , w , w);
            frame.add(button[i][j]);

        }
    }

First of all, the for loop is wrong. You seemed to have messed up the numbers. The two loops should both be = 0 and < 10. Also, I removed these three lines:

    JPanel panel = new JPanel();
    panel.setLayout(null);
    frame.add(panel);

You forgot the initialize the buttons using new JButton(), so I did it for you.

Finally, it is frame.add(button[i][j]) instead of this.add(button[i][j]).

It looks like this:

enter image description here

Comments