Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class Minesweeper extends JFrame
{
private JFrame MainFrame = new JFrame("Minesweeper");
private JButton[][] feld;
private boolean[][] bomben;
Random rand = new Random();
public Minesweeper(int breite, int hoehe, int schwierigkeitsgrad)
{
MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainFrame.getContentPane().setLayout(null);
feld = new JButton[breite][hoehe];
bomben = new boolean[breite][hoehe];
for(int i = 0; i < hoehe; i++)
{
for(int j = 0; j < breite; j++)
{
feld[j][i] = new JButton();
MainFrame.getContentPane().add(feld[j][i]);
feld[j][i].setBounds(16*j + MainFrame.getInsets().left, 16*i + MainFrame.getInsets().top, 16, 16);
int k = rand.nextInt(10);
if(k == 1)
bomben[j][i] = true;
else
bomben[j][i] = false;
feld[j][i].setMnemonic(KeyEvent.VK_I);
feld[j][i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(bomben[j][i])
{
feld[j][i].setText("X");
feld[j][i].setForegroundColor(Color.blue);
}
else
{
int l = 0;
if(bomben[j++][i])
l++;
if(bomben[j][i++])
l++;
if(bomben[j--][i])
l++;
if(bomben[j][i--])
l++;
if(bomben[j++][i++])
l++;
if(bomben[j--][i--])
l++;
if(bomben[j++][i--])
l++;
if(bomben[j--][i++])
l++;
feld[j][i].setText(""+l);
}
}
});
}
}
MainFrame.getContentPane().setBackground(Color.BLUE);
MainFrame.setSize((breite)*16+16, (hoehe+1)*16+22);
MainFrame.setVisible(true);
//MainFrame.setResizable(false);
}
}
ERROR: local variable j (and i) is accessed from within inner class; needs to be declared final.
I have not a single clue how to fix this.. googling didnt help me. i did it once like this but without that for-loop. Any help appreciated!
(this is going to be a minesweeper-game by the way. a 2D array with buttons and one with a boolean that says if it is a bomb or not)
if you have any questions , feel free to ask.
edit: ah das is ja ein deutsches forum (bin neu hier), also Antworten auch gerne auf deutsch.
Zuletzt bearbeitet: