JavaFX让用户设置图片

时间:2015-07-28 12:53:49

标签: java javafx

所以 我试图让用户设置图片的路径,然后显示它,但我无法显示它。

目前,我正在使用Eclipse和Scene Builder来实现我的目标

到目前为止

代码:

            @FXML
            public void choseFile() {
            fc = new FileChooser();
            File tmp = fc.showOpenDialog(dialogStage);
            Image img = new Image(tmp.getAbsolutePath);
            image1 = new ImageView();
            image1.setImage(img);
            }

image1在SceneBuilder中设置为ImageView,而chooseFile()方法设置为该图片旁边的按钮

提前致谢

1 个答案:

答案 0 :(得分:-1)

如James_D所述,您需要在代码中添加ImageView

导入javax.scene.image.ImageView

根据文档

  

ImageView是一个节点,用于绘制加载有Image类的图像。此类允许调整显示图像的大小(保留或不保留原始宽高比),并通过限制此ImageView显示的像素来指定源图像中的视口。


示例代码

public class HelloMenu extends Application {

     @Override public void start(Stage stage) {
         // load the image
         Image image = new Image("flower.png");

         // simple displays ImageView the image as is
         ImageView iv1 = new ImageView();
         iv1.setImage(image);

         // resizes the image to have width of 100 while preserving the ratio and using
         // higher quality filtering method; this ImageView is also cached to
         // improve performance
         ImageView iv2 = new ImageView();
         iv2.setImage(image);
         iv2.setFitWidth(100);
         iv2.setPreserveRatio(true);
         iv2.setSmooth(true);
         iv2.setCache(true);

         // defines a viewport into the source image (achieving a "zoom" effect) and
         // displays it rotated
         ImageView iv3 = new ImageView();
         iv3.setImage(image);
         Rectangle2D viewportRect = new Rectangle2D(40, 35, 110, 110);
         iv3.setViewport(viewportRect);
         iv3.setRotate(90);

         Group root = new Group();
         Scene scene = new Scene(root);
         scene.setFill(Color.BLACK);
         HBox box = new HBox();
         box.getChildren().add(iv1);
         box.getChildren().add(iv2);
         box.getChildren().add(iv3);
         root.getChildren().add(box);

         stage.setTitle("ImageView");
         stage.setWidth(415);
         stage.setHeight(200);
         stage.setScene(scene); 
         stage.sizeToScene(); 
         stage.show(); 
     }

     public static void main(String[] args) {
         Application.launch(args);
     }
 }