I'm supposed to make a connect four game in gridworld with Pieces as the discs but my teacher for some reason told us nothing about the mouselistener! so i did look it up a little but i still cant figure out how to add a mouse listener to the grid to track mouse clicks.
PS: If you really want the code for the Piece class i can add it, and im pretty sure that World extends Jframe.
import java.awt.Color;
import java.util.ArrayList;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
import info.gridworld.world.World;
import info.gridworld.grid.BoundedGrid;
import java.awt.MouseInfo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class ConnectFourWorld extends World<Piece> implements MouseListener
{
private String whosTurn;
private boolean gameOver;
private String winner;
Piece X = new Piece("ex", Color.WHITE, Color.RED);
Piece O = new Piece("oh", Color.YELLOW, Color.BLUE);
public ConnectFourWorld()
{
super(new BoundedGrid<Piece>(6,7));
winner="no winner";
whosTurn="X";
gameOver=false;
setMessage("Welcome to Connect Four World! - - Click a spot - "+whosTurn+"'s turn.");
}
public boolean locationClicked(Location loc)
{
Grid<Piece> grid = getGrid();
if(grid == null)
return false;
if(grid.get(loc)!=null)
return false;
if(gameOver == true)
{
return false;
}
return true;
}
public Location addPiece(Location loc)
{
return null;
}
public void step()
{
}
public boolean isWorldFull()
{
return false;
}
public void resetWorld()
{
}
public String getWinner(Location loc)
{
return "";
}
@Override
public void mouseClicked(MouseEvent e) {
if(e.getButton()==1&&whosTurn.equals("X")){
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
No. The instance variable of the World class are:
public class World<T>
{
private Grid<T> gr;
private Set<String> occupantClassNames;
private Set<String> gridClassNames;
private String message;
private JFrame frame;
private static Random generator = new Random();
private static final int DEFAULT_ROWS = 10;
private static final int DEFAULT_COLS = 10;
...
}
So in fact World is not a JFrame, but in fact has one, which is inaccessible because it's private. You could, however, create your own world class that merely changes the private JFrame to a protected JFrame, and then extend that. You could then access the JFrame and add a mouse Listener by using
WorldVariableName.frame.addMouseListener(new listener).
P.S. I've always thought it better to create a separate private MouseListener class in the main class rather than implementing MouseListener in the main class.