I've two classes in my program that need to communicate with each other (Tile, Field)
The Tile class implement a MouseListener, when the user clicks on the Tile, I want the Field class to get notified.
I know how to achieve this in C#, Objective-c or Swift, but I've no idea how to do it in Java.
This is the code of the Tile class
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import org.omg.CORBA.Current;
public class Tile extends JButton implements MouseListener {
private static final long serialVersionUID = -2445981172620162110L;
public boolean isBomb;
private int posX;
private int posY;
public enum TileState {
HIDDEN, MARKED, EXPOSED
}
private TileState currentState;
public Tile(int posX, int posY) {
this.currentState = TileState.HIDDEN;
this.addMouseListener(this);
this.setOpaque(true);
this.setBorder(new LineBorder(Color.darkGray, 1));
this.setBackground(Color.lightGray);
this.posX = posX;
this.posY = posY;
this.isBomb = this.generateBomb();
if(this.isBomb) {
this.setBackground(Color.blue);
}
}
private void changeIcon(TileState state) {
}
private boolean generateBomb() {
return (new Random().nextInt(5) + 1 ) == 5 ? true : false;
}
private void changeCurrentState(TileState newState) {
if (newState != null) {
this.currentState = newState;
this.changeTileColor(newState);
}
}
private void changeTileColor(TileState tileState) {
switch (tileState) {
case EXPOSED:
this.setBackground(Color.white);
break;
case HIDDEN:
this.setBackground(Color.lightGray);
break;
case MARKED:
this.setBackground(Color.red);
break;
}
}
public int getXPosition() {
return this.posX;
}
public int getYPosition() {
return this.posY;
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if (e.getButton() == MouseEvent.BUTTON1 || e.getButton() == MouseEvent.BUTTON3) {
TileState newState = null;
if (e.getButton() == MouseEvent.BUTTON1) {
System.out.println("Left Click");
if (this.currentState == TileState.MARKED) {
newState = TileState.HIDDEN;
} else if (this.currentState == TileState.HIDDEN) {
newState = TileState.EXPOSED;
}
}
else if (e.getButton() == MouseEvent.BUTTON3) {
System.out.println("Right Click");
if (this.currentState != TileState.EXPOSED) {
newState = (this.currentState == TileState.MARKED) ? TileState.HIDDEN : TileState.MARKED;
}
}
this.changeCurrentState(newState);
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}