0

我正在使用 FXML,并且在一个舞台上有两个不同的场景。btnStart 在scene1,imgBtn 在scene2。当我单击 btnStart 时,它会将 scene2 设置为舞台并将图像加载到 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);
}
4

1 回答 1

2

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

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

  1. FXML 文件
  2. 控制器类
  3. Scene目的。

应该这样做:

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")));
    }
}
于 2018-02-13T06:09:20.477 回答