Thursday, June 7, 2012

JavaFX 2: Add Image to Button

This is a tutorial about how to add image to button with JavaFX 2. As you can see from the image below, we will have 3 buttons with images. Two of them will have just only images, but one of  them will have image and text.

Important: Do not forget to add images to /src folder of our project.
 Here are the pictures:  

Here is the code of our example:


  1. Here is my Code, how it goes with fxml,

  2. I haven't tried do this with CSS, but if you want, you are free to try it. If you succeed to do that, let me know. I could write a blogpost, because that sounds very interesting.

  3. On trying the same code i get this error,how to clear it ?
    Exception in Application start method
    Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(
    at com.sun.javafx.application.LauncherImpl.access$000(
    at com.sun.javafx.application.LauncherImpl$
    Caused by: java.lang.NullPointerException: Input stream must not be null
    at javafx.scene.image.Image.validateInputStream(
    at javafx.scene.image.Image.(
    at imageToButton.start(
    at com.sun.javafx.application.LauncherImpl$
    at com.sun.javafx.application.PlatformImpl$
    at com.sun.javafx.application.PlatformImpl$
    at Method)

  4. You have null pointer on 50th line of the code.

  5. yes the place where i add the image to the button, i have the image at the right path but i don't know why do i get such error..

  6. This comment has been removed by the author.

  7. I have tried to add an image in this way:
    Image img1 = new Image("file:///C:/Users/prem/IdeaProjects/imageToButton/about.png"); then it works perfect but i get nullpointerexception on using this code: Image img1 = new Image(getClass().getResourceAsStream("about.png")); may i know why ?

  8. in order to allow to work also in Eclipse running under Windows OS you have to put the .png files under the base home path of the project, for example C:\develop.eclipse\imageToButton\about.png where C:\develop.eclipse\imageToButton is the home path of the project, the parent of src/ and /bin

  9. Sorry,... the quickest, simplest and better hint his to place the .png files in the same directory of imageToButton.jar executable ... it was almost obvious ;-) to workaround


  10. For those who have NullPointException try to add a slash before image name

    Image(getClass().getResourceAsStream("/about.png")); if the images are located in src folder .

  11. Here is my code:
    Image locki = new Image(getClass().getResourceAsStream("/lock.png"));
    ImageView lock = new ImageView(locki);

    Button b1 = new Button("1"); b1.setOnAction(e -> select(1));
    Button b2 = new Button(lock); b2.setOnAction(e -> select(1));

    Eclipse underlines my call for the ImageView, and when I compile my project it prints out a list of errors.