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 ?
You can add a graphic object (node) to a button using the setGraphic() method of the Button class (inherited from 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.
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.
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));
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With