1

I am trying to set an image to a button but I can't get a working result. My button is located in gridpane.

Image mine = new Image(new File("..some path").toURI().toString());
ImageView im = new ImageView(mine);

im.setFitHeight(btn.getHeight());
im.setFitWidth(btn.getWidth());
btn.setGraphic(im);

How can I do this?

I'm trying add to panel, but sometimes button was removed and I didnt get button with image.

private static void setFlag(Button btn,int x,int y,GridPane gridPane){
        Image mine = new Image(new File("some path..").toURI().toString());
        ImageView im = new ImageView(mine);

        im.setFitHeight(btn.getHeight());
        im.setFitWidth(btn.getWidth());
        btn.setGraphic(im);

        gridPane.add(btn, y, x);
    }

This method is called when a button is pressed. Before that I used another method, where I used label and this method worked.

private static void setBombCell(Button btn, int x,int y,GridPane gridPane){
        Image mine = new Image(new File("..").toURI().toString());
        ImageView im = new ImageView(mine);

        Label label = new Label();


        label.setMaxWidth(Double.MAX_VALUE);
        label.setMaxHeight(Double.MAX_VALUE);
        GridPane.setHgrow(label, Priority.ALWAYS);
        GridPane.setVgrow(label, Priority.ALWAYS);

        im.setFitHeight(btn.getHeight());
        im.setFitWidth(btn.getWidth());
        label.setGraphic(im);
        gridPane.add(label, y, x);
    }
Saliery
  • 155
  • 5
  • 16
  • @Slaw I've rewrote – Saliery Nov 24 '19 at 14:51
  • By default `Button` adds some insets to the graphic. Even if you get this to work, the button and therefore the row+column will grow... Furthermore I recommend reusing the `Image` data. You can display the same `Image` data in an arbitrary number of `ImageView`s. Also I recommend store the image data as resource. BTW: `File` objects do not distinguish between existing and non-existing files. Are you sure the file path is correct? – fabian Nov 24 '19 at 16:09
  • @fabian path is correct, when I used gridpane method add, I get button with image, but sometimes buttons were removed and I got empty cells – Saliery Nov 24 '19 at 17:21
  • @fabian I'm trying to write minesweeper and this method should add image flag to the button – Saliery Nov 24 '19 at 17:24
  • [mcve] please.. – kleopatra Nov 24 '19 at 22:55

1 Answers1

0

I solved this problem. I used method button.setStyle("") for this.

Saliery
  • 155
  • 5
  • 16