How can I show an image using the ImageView component in javafx and fxml?

前端 未结 7 1968
感情败类
感情败类 2020-12-03 14:21

I suppose it\'s a very simple thing but I just can\'t get behind it. All I want is to show an image over an ImageView linked to fxml. Here is my code:

packag         


        
7条回答
  •  悲&欢浪女
    2020-12-03 15:08

    If you want to use FXML, you should separate the controller (like you were doing with the SampleController). Then your fx:controller in your FXML should point to that.

    Probably you are missing the initialize method in your controller, which is part of the Initializable interface. This method is called after the FXML is loaded, so I recommend you to set your image there.

    Your SampleController class must be something like this:

    public class SampleController implements Initializable {
    
        @FXML
        private ImageView imageView;
    
        @Override
        public void initialize(URL location, ResourceBundle resources) {
            File file = new File("src/Box13.jpg");
            Image image = new Image(file.toURI().toString());
            imageView.setImage(image);
        }
    }
    

    I tested here and it's working.

提交回复
热议问题