如何在Java FX中动态加载ImageView中的图像

时间:2018-02-13 05:51:43

标签: javafx nullpointerexception fxml image-viewer

我正在使用FXML,并且在一个舞台上有两个不同的场景。 btnStart在scene1上,imgBtn在scene2上。当我单击btnStart时,它将scene2设置为stage并将图像加载到imageView(这会抛出NullPointerException)。但是当我在scene2上点击imgBtn时,它正在加载图片。

我的问题是当我切换到scene2时如何动态加载图像?

@FXML private Button imgBtn;
@FXML private Button btnStart;
@FXML public ImageView imageView;

@FXML
public void imgBtnClicked()throws Exception{      
    imageView.setImage(new Image(new FileInputStream("src/Assets/CardAssets/png-v2/3C.png")));
}


@FXML
public void btnStartClicked()throws Exception{
    SetScene2();
    imageView.setImage(new Image(new FileInputStream("src/Assets/CardAssets/png-v2/3C.png")));

}  

public void SetScene2()throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource(fxmlFile2.fxml));
    String css=getClass().getResource("myStyle.css").toExternalForm();
    Scene scene;
    try{
        scene=new Scene(root,root.getScene().getWidth(),root.getScene().getHeight());
    }
    catch(NullPointerException e) {
        scene=new Scene(root,stage.getWidth(),stage.getHeight());
    }
    scene.getStylesheets().add(css);
    stage.setScene(scene);
}

1 个答案:

答案 0 :(得分:1)

问题不是很清楚,所以我想在这里做一些猜测。最可能的问题是你混淆了Node哪个场景在哪个控制器上。

正确的结构是您有以下两项中的两组:

  1. FXML文件
  2. 控制器类
  3. Scene object。
  4. 这是应该做的:

    public class ControllerA {
        @FXML private Button btnStart;
    
        @FXML
        public void btnStartClicked()throws Exception{
            setScene2();
        }  
    
        public void setScene2()throws Exception {
            // You may need to set the controller to an instance of ControllerB,
            // depending whether you have done so on the FXML.
            Parent root = FXMLLoader.load(getClass().getResource(fxmlFile2.fxml));
    
            String css=getClass().getResource("myStyle.css").toExternalForm();
            Scene scene;
            try{
                scene=new Scene(root,root.getScene().getWidth(),root.getScene().getHeight());
            }
            catch(NullPointerException e) {
                scene=new Scene(root,stage.getWidth(),stage.getHeight());
            }
            scene.getStylesheets().add(css);
            stage.setScene(scene);
        }
    
    }
    
    public class ControllerB {
        @FXML private ImageView imageView;
        @FXML private Button imgBtn;
    
        @FXML public void initialize() {
            imageView.setImage(new Image(new FileInputStream("src/Assets/CardAssets/png-v2/3C.png")));
        }
    
        @FXML
        public void imgBtnClicked()throws Exception{      
            imageView.setImage(new Image(new FileInputStream("src/Assets/CardAssets/png-v2/3C.png")));
        }
    }