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.

  1. keep reference of position object in rectangle object. useful if rectangle needs access various datum in container various places. rectangle.getposition().getcoordinates() or .getplayer().
  2. keep reference of coordinates object in rectangle object. more specific approach of 1 useful if need object. rectangle.getcoordinates().
  3. pass coordinates setuprectangle method. useful if rectangle doesn't need access data various places, it's local solution. in handle method return coordinates passed setuprectangle, though can't see class method in.
  4. use external help. can keep map<rectangle, coordinates> , call map.get(rectangle). can hide map in method coordinates getcoordinatesforrectangle(rectangle rectangle) instead of calling directly.

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -