java - JavaFX rectangle mouseonclick grid return -
i writing board game has 20x20 grid.
this in board class:
private final position[][] grid = new position[grid_size][grid_size];
each position has :
public class position { private final coordinates pos; private player player; private final static double rectangle_size = 40.0; private final rectangle rect = new rectangle(rectangle_size, rectangle_size); }
so have 20x20 positions , each positions has rectangle
this display grid
for (int cols = 0; cols < grid_size; ++cols) { (int rows = 0; rows < grid_size; ++rows) { grid.add(gameengine.getboard().getgrid()[cols][rows].getrect(), cols, rows); } }
anyway, grid initialized , works properly. want make rectangle objects clickable , able return coordinates when clicked.
this how handle mouse click
private void setuprectangle() { rect.setonmouseclicked(new eventhandler<mouseevent>() { @override public void handle(mouseevent event) { rect.setfill(color.black); } }); }
what code change color of rectangle black, how return coordinates. basically, can edit onclick function return coordinates of position, how can acquire them later?
this not javafx question as design question. have container (position
) of 2 objects (coordinates
, rectangle
) , want 1 of them know other. is, rectangle should know coordinates of position.
there few approaches here, , depending on bigger picture, 1 might better others. james_d mentioned couple in comment.
- keep reference of position object in rectangle object. useful if rectangle needs access various datum in container various places.
rectangle.getposition().getcoordinates()
or.getplayer()
. - keep reference of coordinates object in rectangle object. more specific approach of 1 useful if need object.
rectangle.getcoordinates()
. - pass coordinates
setuprectangle
method. useful if rectangle doesn't need access data various places, it's local solution. inhandle
method return coordinates passedsetuprectangle
, though can't see class method in. - use external help. can keep
map<rectangle, coordinates>
, callmap.get(rectangle)
. can hide map in methodcoordinates getcoordinatesforrectangle(rectangle rectangle)
instead of calling directly.
Comments
Post a Comment