Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change image of button in javaFX?

I am using javaFX. I made a button and set an image for this . the code is :

    Image playI=new Image("file:///c:/Users/Farhad/Desktop/icons/play2.jpg");
    ImageView iv1=new ImageView(playI);
    iv1.setFitHeight(67);
    iv1.setFitWidth(69);

    Button playB=new Button("",iv1);

But i want to when i click the button , image changes to another picture. How can i do this ?

like image 685
Eng.sabbath Avatar asked Jul 18 '15 22:07

Eng.sabbath


People also ask

Can you set a image as button JavaFX?

You can add a graphic object (node) to a button using the setGraphic() method of the Button class (inherited from javafx.

How to change color of button JavaFX?

Here is an example setting the background color of a JavaFX button to red: Button button = new Button("My Button"); button. setStyle("-fx-background-color: #ff0000; "); This example sets the style directly on the button via the setStyle() method, but you can also style a JavaFX button via style sheets.

How to add images JavaFX?

Create a FileInputStream representing the image you want to load. Instantiate the Image class bypassing the input stream object created above, as a parameter to its constructor. Instantiate the ImageView class. Set the image to it by passing above the image object as a parameter to the setImage() method.


1 Answers

You could set the buttons Graphic in an Action

Image image = new Image(getClass().getResourceAsStream("play3.jpg"));
button.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent e) {
        Button button = (Button) e.getSource();
        button.setGraphic(new ImageView(image));
    }
});
like image 101
Reimeus Avatar answered Sep 20 '22 06:09

Reimeus