嵌入ImageView事件处理程序>>>无法正常工作

时间:2015-10-04 06:41:12

标签: java javafx imageview

我是初学java学生。我正在尝试编写一个简单的程序,在单击按钮时将显示本地保存的图像。图片无法加载。代码如下所示。任何帮助表示赞赏。请记住我的技能水平。

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);
    }
}

1 个答案:

答案 0 :(得分:0)

您需要做的是将您BorderPane添加到ImageView的{​​{1}}添加到场景中的节点。最简单的方法是将其添加到VBox pane。然后你需要将pane填充到事件处理程序:

@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);
}