I'm programming an easy version of BlackJack in javafx but I lost my road home I guess! I need to show cards in 2 rows when I click hit button.
How can I add different images in a row when I click a button? I tried to use GridPane
and BorderPane
but the images are shown at the same place... I know I need a for loop for each time I press the button but I'm not sure how to do it.. I made the same game in java swing and it went well
here is my loadImage
method
public void ImageloadP(Card xPCard) {
String xP = xPCard.toString();
Image card = new Image("file:/Users/cetabije/Desktop/Apa/src/cards.png/" + xP + ".png");
ImageView xPv = new ImageView(card);
xPv.setFitHeight(140);
xPv.setFitWidth(95);
root.getChildren().add(xPv);
}
This can be done with a GridPane
, but you have to specify the column/row index to prevent the Node
s to be placed at the same position.
The following example uses Rectangle
s for simplicity, but it works with any Node
type:
private Color color = Color.BLACK;
@Override
public void start(Stage primaryStage) {
GridPane gridPane = new GridPane();
gridPane.setHgap(10);
gridPane.setVgap(10);
Button btn = new Button("Add Rect");
// add node specifying column and row index
gridPane.add(btn, 0, 0);
gridPane.setStyle("-fx-background-color: lime;");
btn.setOnAction((ActionEvent event) -> {
color = color.brighter();
Rectangle rectangle = new Rectangle(20, 20);
rectangle.setFill(color);
// append rect to second row
gridPane.addRow(1, rectangle);
});
Scene scene = new Scene(gridPane, 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
Note that if you use gridPane.getChildren().add(node)
the default column/row index (0
) is used, unless a different position is assigned in the properties of node
using GridPane.setConstraints
, GridPane.setRowIndex
or GridPane.setColumnIndex
Note that BorderPane
is not the correct Parent
to display multiple nodes next to each other unless they fit the "role" of top, left, center, right and/or bottom node (which isn't the case in your scenario).