I've wrote the inner class in a loop.but of course i and j won't be the i and j above and if I use static variables I'll have NullPointerException and also I can't make objects.
and I don't know how to find the index of the component from the layout.(I've commented methods I tried,but that seems wrong).
generally I don't understand inner classes and how variables work in them.
it's just the begging of the program and I've just built the buttons
and I don't know even if my algorithm is correct because I've couldn't try it yet.
:
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MineSweeper {
static int [][]nearbyBombs;
static boolean [][] inBomb=new boolean[9][9];
static Button [][] cells=new Button[9][9];
static int x,y;
public static void main(String[] args) {
JFrame myFrame=new JFrame("MineSweeper");
GridLayout myGrid=new GridLayout(9,9);
myGrid.setHgap(-5);
myGrid.setVgap(-5);
JPanel upperPanel=new JPanel();
myFrame.add(upperPanel,BorderLayout.NORTH);
JPanel myPanel=new JPanel(myGrid);
myFrame.add(myPanel);
for (int i=0;i<10;){
int x=(int)(Math.random()*9);
int y=(int)(Math.random()*9);
if(!inBomb[x][y]){
inBomb[x][y]=true;
i++;
}
}
for (int i=0;i<9;i++){
for(int j=0;j<9;j++){
cells[i][j]=new Button();
myPanel.add(cells[i][j]);
x=i;
y=j;
cells[i][j].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
/* MineSweeper.x=((Button)e.getSource()).getWidth();
MineSweeper.y=((Button)e.getSource()).getHeight();*/
for(int i=(x-1);(i<(x+1))&&(0<i && i<9);i++)
for(int j=(y-1);(j<(y+1))&&(0<j && j<9);j++)
nearbyBombs[x][y]++;
((Button)e.getSource()).setLabel(""+nearbyBombs[x][y]);
}
}
);
}
}
myFrame.setVisible(true);
}
}

New Topic/Question
Reply




MultiQuote





|