The solution is probably staring at me in the face. But here's my problem.
Take a look at this method:
public void showUserData() {
int numUsers = usersModel.numberOfUsers(); // number of users(rows) in the database
ColumnConstraints column1 = new ColumnConstraints();
column1.setPercentWidth(40);
ColumnConstraints column2 = new ColumnConstraints();
column2.setPercentWidth(60);
int counter = 0;
for(int i = 0; i <= numUsers - 1; i++) {
subGrid = new GridPane();
subGrid.getColumnConstraints().addAll(column1, column2);
userImage = new ImageView();
subGrid.setStyle("-fx-background-color: #dddddd;");
subGrid.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
System.out.println("mouse click detected! " + mouseEvent.getSource());
subGrid.setStyle("-fx-background-color: blue;");
}
});
vbox = new VBox();
vbox.getChildren().add(new Label("Name: " + getUserData().get(counter)));
vbox.getChildren().add(new Label("Username: " + getUserData().get(counter + 1)));
vbox.getChildren().add(new Label("Position: " + getUserData().get(counter + 2)));
subGrid.add(vbox, 1, 0);
user = new Image("file:///" + getUserImage().get(i));
userImage.setFitWidth(150);
userImage.setFitHeight(150);
userImage.setSmooth(true);
userImage.setPreserveRatio(true);
userImage.setImage(user);
subGrid.add(userImage, 0, 0);
if(i % 2 == 0 && i == 0) {
mainGrid.add(subGrid, 0, 0);
} else if (i % 2 == 0 && i != 0){
mainGrid.add(subGrid, 0, i - 1);
} else {
mainGrid.add(subGrid, 1, i - 1);
}
scroll.setContent(mainGrid);
counter = counter + 3;
}
}
I know its a mess but hear me out. I have a ScrollPane, and inside is a GridPane that spans the entire area of the ScrollPane. In every cell of the GridPane, there is another smaller GridPane. In each of these smaller GridPanes, the left column is an ImageView and the right is a VBox with labels in it.
The long and the short of this method is that:
a. It takes the number of rows in the database.
b. It creates a subGrid for every row in the database (corresponding to the number of users in the table).
c. It creates the ImageViews and VBoxes for each of the subGrids and adds them in.
d. It then takes the subGrids and adds it to the mainGrid.
This process works. But the listener only works on the latest subGrid that was added. i.e. second subGrid lights up, first does not, third subGrid lights up, second does not, etc.
I'm not sure if TableView can work with this. That's why I tried it with GridPane first. Why does my listener not work?
I ama beginner at this. I know the method is a mess. I know I need to refactor some things. But as long, as I can get this to work, I will happily clean it up afterwards. Any help appreciated, thank you.