简体   繁体   中英

JavaFX let user set a picture

So I am trying to let the user set a path to a picture and then display it but I am not able to display it.

Currently, I am using Eclipse and Scene Builder to accomplish my goals

Code so far:

@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 is set to an ImageView in the SceneBuilder and the choseFile() method is set to a button that is next to that picture

Thanks in advance

As James_D mentioned, you need to add ImageView in your code.

Import javax.scene.image.ImageView .

According to the documentation,

The ImageView is a Node used for painting images loaded with Image class. This class allows resizing the displayed image (with or without preserving the original aspect ratio) and specifying a viewport into the source image fro restricting the pixels displayed by this ImageView.


Sample code from the document :

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM