Share the post "How To Create Clickable ImageView Or Image Button In Java FX 2"
In Swing, an image button is possible by setting the background color of the JButton to transparent and the image will still show its pressed and normal state effect when clicked.
In Java FX 2 however, when you add an image to the Button control and set the background to transparent using -fx-background-color: transparent, you are left with a static image that does not move whenever you click on it.
There is no ready made class in Java FX 2 that does this so the only solution left is to make one. What I did is extend from Button class and simulate the pressed and released effect by changing the padding values whenever a mouse event occurs.
That’s it! It is as simple as that.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class ImageButton extends Button { private final String STYLE_NORMAL = "-fx-background-color: transparent; -fx-padding: 5, 5, 5, 5;"; private final String STYLE_PRESSED = "-fx-background-color: transparent; -fx-padding: 6 4 4 6;"; public ImageButton(String imageurl) { setGraphic(new ImageView(new Image(getClass().getResourceAsStream(imageurl)))); setStyle(STYLE_NORMAL); setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { setStyle(STYLE_PRESSED); } }); setOnMouseReleased(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { setStyle(STYLE_NORMAL); } }); } } |
Thanks for the great tip, I’m using your class in my application and I gave you credit.
Thanks for the tip. In fact, the image button is very useful and is missing in JavaFX.
Taking advantage of your experience, do you have any tips for generating an interesting hover effect for an image button? (MouseEntered / MouseExited)