-2
對於一個學校項目,我一直在開展掃雷遊戲。它本質上將成爲遊戲的一個克隆,但現在,當我嘗試爲JButton添加動作偵聽器時,我得到了一個nullpointerexception
。任何幫助?這是我的代碼:添加ActionListener時數組中的空指針異常
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.GridLayout;
import java.awt.Dimension;
import java.util.Random;
public class Grid {
public static int c, d; //Necessary for the allowance of usage within the listeners from lines 47 - 68.
JFrame frame = new JFrame();
public static boolean[][] isBomb;
public static int bombProbability;
public static JButton[][] grid;
Random Bomb = new Random();
public Grid(int width, int length){
bombProbability = (int) Double.parseDouble(JOptionPane.showInputDialog("Input the likeliness of a bomb:"));
frame.setLayout(new GridLayout(width, length));
grid = new JButton[width][length];
isBomb = new boolean[width + 2][length + 2];
for(int a = 1; a <= length; a++){
for(int b = 1; b <= width; b++){
grid[a][b] = new JButton();
frame.add(grid[a][b]);
if((Bomb.nextInt(99) + 1) <= bombProbability){
isBomb[a][b] = true;
grid[a][b].setText(String.valueOf(isBomb[a][b])); //Delete this before final product
}
}
}
frame.setTitle("Minesweeper!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(500, 500));
frame.pack();
frame.setVisible(true);
for(c = 0; c < length; c++){
for(d = 0; d < width; d++){
grid[c][d].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(isBomb[c][d] == true){
JOptionPane.showMessageDialog(null, "BOOM! You're DEAD!");
System.exit(0);
}
else{
indexCells(c,d);
}
}
});
}
}
}
public static void indexCells(int c,int d){
int[][] nearbyBombs = new int[c+2][d+2];
for (int i = 1; i <= c; i++){
for (int j = 1; j <= d; j++){
// (ii, jj) indexes neighboring cells
for (int ii = i - 1; ii <= i + 1; ii++){
for (int jj = j - 1; jj <= j + 1; jj++){
if (isBomb[ii][jj]){
nearbyBombs[i][j]++;
}
}
}
grid[i][j].setText(String.valueOf(nearbyBombs[i][j]));
if(nearbyBombs[i][j] == 0){
for(int iii = i - 1; iii <= i + 1; iii ++){
for(int jjj = j - 1; jjj <= j + 1; jjj ++){
indexCells(iii,jjj);
}
}
}
}
}
}
public static void main(String []args){
//int columns = (int) Double.parseDouble(JOptionPane.showInputDialog(null, "Input the number of columns:"));
//int rows = (int) Double.parseDouble(JOptionPane.showInputDialog(null, "Input the number of rows:"));
new Grid(10, 10);
}
}
問題是與行54(grid[c][d].addActionListener(new ActionListener() {
)。任何幫助將不勝感激。
why(int a = 1; a <=長度; a ++){(int b = 1; b <= width; b ++){你用a開始a和b? – 2014-11-25 01:11:30
它給了我這個錯誤線程「主」java.lang.ArrayIndexOutOfBoundsException異常:10? – 2014-11-25 01:15:14
我已經得到了,但沒有與此版本的代碼...我不知道這是怎麼發生的。 – 2014-11-25 01:18:22