I built a game that built an matrix of labels i add the labels an mouselistener and The problem is that when I press event on a
particular label, say there is map[0][0] It create an event no matter what I click .... How do I create a matrix of labels when I do certain conditions on each label was only then that event will happen
sorry about my english
this is my code:
public class Board { private int x; private int y; private Point location; private ImageIcon picture; private JLabel label; private Piece[][] map; public Board() { this.x = 47; this.y = 45; this.location = new Point(); this.map = new Piece[9][12]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 12; j++) { this.map[i][j] = new Piece(new Point(), null, new JLabel(), 0, false); } } } public Piece[][] getMap() { return this.map; } public void setMap(Piece[][] map) { this.map = map; } public void draw(Panelmenu panel) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 12; j++) { this.location.setX(this.x); this.location.setY(this.y); System.out.println("[" + i + ", " + j + "] = [X=" + this.x +", Y=" + this.y + "]"); this.map[i][j].setLocation(this.location); System.out.println("[" + i + ", " + j + "] = [Point = " + this.map[i][j].getLocation() + "]"); this.picture = new ImageIcon(getClass().getResource("images/stone.png")); this.map[i][j].setPicture(this.picture); this.label = this.map[i][j].getLabel(); this.label.setText(""); this.label.setIcon(this.map[i][j].getPicture()); this.label.setHorizontalAlignment(JLabel.CENTER); this.label.setSize(58, 58); this.label.setLocation(this.x, this.y); this.map[i][j].setLabel(this.label); this.map[i][j].setType(0); this.map[i][j].setStatus(true); this.x += 62; if (j == 11) { this.x = 47; this.y += 59; } this.map[i][j].draw(panel); } } } }
this is the Piece class:
public class Piece implements MouseListener { private Point location; private ImageIcon picture; private JLabel label; private int type; private boolean status; public Piece(Point location, ImageIcon picture, JLabel label, int type, boolean status) { this.location = location; this.picture = picture; this.label = label; this.type = type; this.status = status; this.label.addMouseListener(this); } public Point getLocation() { return this.location; } public void setLocation(Point location) { this.location = location; System.out.println("Piece = " + this.location); } public ImageIcon getPicture() { return this.picture; } public void setPicture(ImageIcon picture) { this.picture = picture; } public JLabel getLabel() { return this.label; } public void setLabel(JLabel label) { this.label = label; } public int getType() { return this.type; } public void setType(int type) { this.type = type; } public boolean getStatus() { return this.status; } public void setStatus(boolean status) { this.status = status; } public void draw(JPanel panel) { panel.add(this.label); } @Override public void mouseClicked(MouseEvent e) { System.out.println("[" + this.location.getX() + ", " + this.location.getY() + "]"); }