-3

trying set image to button, but receive NullPointerException.

structure:

resources
  com.example.test
    images
      file_open_icon.png

and code:

openImageview.setImage(new Image(Objects.requireNonNull(getClass().getResourceAsStream("images/file_open_icon.png"))));

Button:

<ToolBar prefHeight="40.0" prefWidth="200.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="25.0">
    <Button fx:id="toolbarHandleOpen" mnemonicParsing="false" onAction="#handle_open">
     <graphic>
        <ImageView fx:id="openImageview" fitHeight="23.0" fitWidth="23.0" pickOnBounds="true" preserveRatio="true" />
     </graphic>
    </Button>
</ToolBar>
  • 2
    See [display image with scenebuilder](https://stackoverflow.com/questions/42558641/display-an-image-with-scenebuilder) and [resource resolution](https://stackoverflow.com/questions/61531317/how-do-i-determine-the-correct-path-for-fxml-files-css-files-images-and-other). If you want debugging help, provide a [mcve] and a stack trace formatted as code. – jewelsea Jan 24 '22 at 11:59
  • Of course I can add via scenebuilder and it works, but i need add via the code. – Енот Полоскун Jan 25 '22 at 08:11
  • If you follow the provided resource lookup advice and have no other errors, setting the image in the view by code will work fine. – jewelsea Jan 25 '22 at 12:22

1 Answers1

1

I had tried to set the picture in the controller constructor, which caused the null pointer exception because the ImageView was not initialized at that time.

I moved the call to set the image to the controller initialize() method and it worked fine.

jewelsea
  • 150,031
  • 14
  • 366
  • 406