如何在运行时在JavaFX中添加ImageView组件

时间:2018-08-22 15:32:59

标签: javafx

实际上,我在一个卡在问题中的项目上工作,我需要通过单击运行时上的按钮来添加ImageView组件,是否有帮助?这是YOur帮我的一件大事。

MainClass

public class See extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

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

}

控制器

public class FXMLDocumentController implements Initializable {

    @FXML
    private Button button;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        File fil=new File("src\\see\\unshadedLaptop.png");
        Image im=new Image(fil.toURI().toString());
        ImageView view=new ImageView(im);
        view.prefHeight(200);
        view.prefWidth(200);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        File fil=new File("src\\see\\unshadedLaptop.png");
        Image im=new Image(fil.toURI().toString());
        ImageView view=new ImageView(im);

    }

}

1 个答案:

答案 0 :(得分:1)

一种方法是在您的Node中给fx:id一个FXML。然后执行@FXML YourNodeType yourNodeFxId;。然后在Button事件处理程序中执行yourNodeFxId.getChildren().add(theImageViewHere);

使用您的代码显示示例:

public class FXMLDocumentController implements Initializable {

    @FXML
    private Button button;
    @FXML 
    private Pane pane;//This is just an example. Make sure you have a  Pane with an fx:id="pane" in your FXML.

    @FXML
    private void handleButtonAction(ActionEvent event) {
        File fil=new File("src\\see\\unshadedLaptop.png");
        Image im=new Image(fil.toURI().toString());
        ImageView view=new ImageView(im);
        pane.getChildren().add(view);//This is the added code.
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO        
    }    
}