The code is working fine.When i left click it does everything the code discribes.The only problem is that i don't want to click an the same spot!I can't find a solution to that.Any suggestions?
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
innerCells[i][j] = new JPanel();
innerCells[i][j].setLayout(new BorderLayout());
innerCells[i][j].setBorder(BorderFactory.createLineBorder(lineColor));
innerCells[i][j].setBackground(backgroundColor);
innerCells[i][j].addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
JPanel k = (JPanel) e.getSource();
JLabel l = new JLabel("", JLabel.CENTER);
int x = getRows();
int y = getCols();
for (int r = 0; r < getRows(); r++) {
for (int c = 0; c < getCols(); c++) {
if (innerCells[r][c] == k) {
x = r;
y = c;
}
}
}
if (array[x][y] == 0) {
l.setBackground(k.getBackground());
k.add(l);
k.setBackground(Color.white);
k.revalidate();
} else {
l.setBackground(k.getBackground());
k.add(l);
k.setBackground(Color.red);
k.revalidate();
}
randomHits();
}
Guys thanks for help by i manage to find the solution myself!I had to add only one line of code,i mean only one checking!The solution is
if (k.getComponents().length == 0)
that means if its clicked its not 0.Thank you all for trying!
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
innerCells[i][j] = new JPanel();
innerCells[i][j].setLayout(new BorderLayout());
innerCells[i][j].setBorder(BorderFactory.createLineBorder(lineColor));
innerCells[i][j].setBackground(backgroundColor);
innerCells[i][j].addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
JPanel k = (JPanel) e.getSource();
JLabel l = new JLabel("", JLabel.CENTER);
int x = getRows();
int y = getCols();
for (int r = 0; r < getRows(); r++) {
for (int c = 0; c < getCols(); c++) {
if (innerCells[r][c] == k) {
x = r;
y = c;
}
}
}
if (k.getComponents().length == 0) {
if (array[x][y] == 0) {
l.setBackground(k.getBackground());
k.add(l);
k.setBackground(Color.white);
k.revalidate();
} else {
l.setBackground(k.getBackground());
k.add(l);
k.setBackground(Color.red);
playerhit++;
GameScreen.FinalWinner();
k.revalidate();
}
randomHits();
}
}