I'm a beginner java student. I am trying to write a simple program that will display a locally saved image when button is clicked. The picture will not load. Code is shown below. Any help is appreciated. Please bear in mind my skill level.
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.scene.text.*;
import javafx.geometry.*;
import javafx.scene.control.*;
public class PhotoViewer extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Text txtHeading = new Text("Click to see the picture");
txtHeading.setFont(new Font(20));
HBox paneTop = new HBox(txtHeading);
paneTop.setPadding(new Insets(20, 20, 20, 20));
Button btn1 = new Button("Picture");
btn1.setPrefWidth(80);
btn1.setOnAction(e -> btn1_Click());
HBox paneBottom = new HBox(btn1);
VBox pane = new VBox(paneTop, paneBottom);
pane.setPadding(new Insets(20, 20, 20, 20));
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Picture Choice");
primaryStage.show();
}
public void btn1_Click() {
Image img = new Image("file:c:\\users\\sandy\\pictures\\IMG_0127.jpg");
ImageView iview1 = new ImageView(img);
iview1.setFitWidth(300);
iview1.setFitHeight(300);
iview1.setPreserveRatio(true);
BorderPane bpane1 = new BorderPane();
bpane1.setCenter(iview1);
}
}
What you have to do is adding the BorderPane
to which you added your ImageView
to a node that is part of the scene. The easiest way is to add it to the VBox pane
. Then you need to padd pane
to the event handler:
@Override
public void start(Stage primaryStage) {
Text txtHeading = new Text("Click to see the picture");
txtHeading.setFont(new Font(20));
HBox paneTop = new HBox(txtHeading);
paneTop.setPadding(new Insets(20, 20, 20, 20));
Button btn1 = new Button("Picture");
btn1.setPrefWidth(80);
HBox paneBottom = new HBox(btn1);
VBox pane = new VBox(paneTop, paneBottom);
pane.setPadding(new Insets(20, 20, 20, 20));
btn1.setOnAction(e -> btn1_Click(pane));
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Picture Choice");
primaryStage.show();
}
public void btn1_Click(VBox parent) {
Image img = new Image("file:c:\\users\\sandy\\pictures\\IMG_0127.jpg");
ImageView iview1 = new ImageView(img);
iview1.setFitWidth(300);
iview1.setFitHeight(300);
iview1.setPreserveRatio(true);
BorderPane bpane1 = new BorderPane();
bpane1.setCenter(iview1);
parent.getChildren().add(bpane1);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.