Issue
I am writing a "Star Trek" game for fun with Java/JavaFX. My idea is that the main game screen is an 10x10 GridPane of Buttons. All the game pieces (the Enterprise, Klingons, planets, etc) would appear as icons in the buttons. This way, you can click a space object to select it, warp to it, shoot it, etc:
Of course, this is all contingent on being able to assign my little starship images to the appropriate buttons. I've figured out how to apply a background to a button, but when I apply the image, the fit is not good. Here's a screenshot of my game thus far:
The "Enterprise" image sorta fits... but not really. There's got to be a way to stretch the ship to fit the button exactly, but I've yet to find it. I also have to find a way to do this in Java (not CSS or FXML) because the Java code will have to move icons around.
Here's my code:
public void setUpBoard(){
// set up 10x10 GridPane of Buttons...
Image testImage = new Image(getClass().getResourceAsStream("Enterprise.png"));
ImageView testImageView = new ImageView(testImage);
testImageView.setFitWidth(55); // My button is 55 x 37 pixels, according to the FXML
testImageView.setFitHeight(37);
//testImageView.fitWidthProperty().bind(gridButton37.widthProperty()); // This didn't work either
//testImageView.fitHeightProperty().bind(gridButton37.widthProperty());
gridButton37.setGraphic(testImageView);
}
I've been Googling for a few hours, but I can't find a "stretch image to parent" solution that seems to apply here. Is there something I am missing?
Solution
btnTest.setMinSize(55, 37);
btnTest.setMaxSize(55, 37);
Image image = new Image("/view/images/someImage.png", btnTest.getWidth(), btnTest.getHeight(), false, true, true);
BackgroundImage bImage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, new BackgroundSize(btnTest.getWidth(), btnTest.getHeight(), true, true, true, false));
Background backGround = new Background(bImage);
btnTest.setBackground(backGround);
See https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Background.html
Answered By - zlakad
Answer Checked By - Gilberto Lyons (JavaFixing Admin)