2016-09-24 88 views
0

我正在用JavaFX編寫一個簡單的應用程序。我有一個Scene三個ImageViews與一個場景生成器創建和相應的Controller.fxml文件引用。在buttonClick事件中,我想用兩個較大的ImageView替換三個小的ImageView。什麼是正確的做法呢?在JavaFX中更改場景時應該更改控制器嗎?

目前我創建了新的.fxml文件,複製了舊版本中的所有內容並刪除了一個ImageView。這給了我一個LoadException,因爲我的Controller中有一個EventHandler,它引用了刪除的ImageView。我是否也應該更改Controller

+2

每個FXML文件應該有自己的控制器類 –

+0

謝謝你,@James_D。 –

+0

爲什麼你不能在一個控制器中做?例如,只需在VBox中做所有事情。點擊按鈕後,清除Vbox,其中3個ImagesView,然後只添加兩個。這種變化將是動態的。 – BadVegan

回答

0

我的解決方案爲這個簡單的行動。我使用了一個控制器和容器,您可以在其中動態更改內容。在這個解決方案中,我使用一個VBox創建了FXML,並在點擊按鈕後更改了內容。

我不這麼認爲,你應該在這種情況下改變場景。當然,就像James_D寫的那樣,如果你想要這樣做,你應該有一個FXML的控制器。

控制器:

public class PictureChange { 

    @FXML VBox vBox; 
    @FXML Button button; 

    @FXML private void initialize() { 
    ImageView v1 = new ImageView(new Image(this.getClass().getResource("/smallPic.png").toExternalForm())); 
    ImageView v2 = new ImageView(new Image(this.getClass().getResource("/smallPic.png").toExternalForm())); 
    ImageView v3 = new ImageView(new Image(this.getClass().getResource("/smallPic.png").toExternalForm())); 
    vBox.getChildren().addAll(v1, v2, v3); 
    } 

    @FXML private void changePictures() { 
    Image bigImage = new Image(this.getClass().getResource("/bigPic.png").toExternalForm()); 
    ImageView vBig = new ImageView(bigImage); 
    vBox.getChildren().clear(); 
    vBox.getChildren().add(vBig); 
    } 
} 

FXML:

<?xml version="1.0" encoding="UTF-8"?> 
<?import javafx.scene.layout.*?> 
<?import javafx.scene.control.Button?> 
<HBox prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="picture.PictureChange"> 
    <VBox fx:id="vBox"> 
    </VBox> 
    <Button fx:id="button" text="Change Pictures" onAction="#changePictures"/> 
</HBox>