JavaFx: how make a clickable image using scenebuilder
Solution 1
I've never used scene builder, but you can just call setOnMouseClicked(EventHandler<MouseEvent> event)
on the ImageView
object.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ImageClickExample extends Application {
@Override
public void start(Stage primaryStage) {
ImageView img = new ImageView("http://i.stack.imgur.com/oURrw.png");
img.setPickOnBounds(true); // allows click on transparent areas
img.setOnMouseClicked((MouseEvent e) -> {
System.out.println("Clicked!"); // change functionality
});
Scene scene = new Scene(new StackPane(img));
primaryStage.setTitle("Image Click Example");
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Solution 2
1)Create a Button
or (Label
🍄) in SceneBuilder
2)Add an ImageView
to the Button using SceneBuilder
Relevant question:here
3)Use CSS:
1)Inside the `SceneBuilder` or
2)Using an external css file(with styleclass or with css id) as shown above i have added all the three ways(choose one :) ):
.crazyButton{
-fx-background-color:transparent;
-fx-border-color:transparent;
-fx-text-fill:transparent;
}
or
#myButton{
-fx-background-color:transparent;
-fx-border-color:transparent;
-fx-text-fill:transparent;
}
👀 Here you can play with the method setPickOnBounds(true/false);
if you want the transparent areas of the Button
to receive click events.
4)Add an ActionListener
or MouseListener
to the Button
using SceneBuilder
or plain Java Code
Solution 3
Lets start with scenebuilder, open the fxml file. Drag-and-drop ImageView from Scenebuilder library(right panel). Once added, select the ImageView and give it a fx:id "iView" in this case, then goto Code section and add a function name in OnMouseClicked field. I named my function "LoginUser".
Now open the controller file in eclipse IDE.
define the function with @FXML tag:
@FXML
private boolean LoginUser() throws ClassNotFoundException {
Stage mainStage = (Stage) iView.getScene().getWindow();
try {
Parent root = FXMLLoader.load(getClass().getResource("file.fxml"));
Scene scene = new Scene(root);
mainStage.setScene(scene);
mainStage.setTitle("Test Window");
}
catch(Exception e){}
}
Load the fxml file you want to on image click.
Comments
-
mistletoe almost 2 years
I wanted to know how to make clickable image using ImageView which takes me to another FXML using scene builder. I am using eclipse IDE.