2017-03-02 59 views
0

我使用SceneBuilder,3個按鈕和2個ImageView創建了一個小型FXML文件。使用SceneBuilder顯示圖像

我想要做的是:

  1. 在啓動
  2. 運行的應用程序,並顯示2個圖像當按下NEXT按鈕,顯示2個其他圖像。

我的問題是不是swiching圖像,而是顯示一個作爲場景生成器創建的ImageView。

這裏是我的控制器類:

public class Controller { 
    private Button Next; //1st button 
    private Button J2inc; //2nd button 
    private Button J1inc; /3rd button 
    private ImageView Img1; 
    private ImageView Img2; 

    void Inc2(ActionEvent event) { 
     //nothing for the moment 
    } 
    void Inc1(ActionEvent event) { 
     //nothing for the moment 
    } 
    void Nextimg(ActionEvent event) { 
     //nothing for the moment 
    } 
} 

而且我start方法:

public void start(Stage primaryStage) throws Exception { 
    Parent root = FXMLLoader.load(getClass().getResource("Css.fxml")); 
    Scene scene = new Scene(root); 
    primaryStage.setScene(scene); 
    primaryStage.setTitle("P "); 
    primaryStage.show(); 
} 

我不知道如何初始化ImageView img1所以它加載的東西。

無法在這裏添加FXML,所以我就只加了ImageView的行:

<ImageView fx:id="Img1" fitHeight="750.0" fitWidth="450.0" layoutY="22.0" pickOnBounds="true" preserveRatio="true" AnchorPane.bottomAnchor="50.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="450.0" AnchorPane.topAnchor="25.0" /> 
+0

「無法添加FXML」是什麼意思?如果您需要知道如何格式化代碼,請閱讀[this](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks)。另外請注意,如果您使用[適當的命名約定](https://en.wikipedia.org/wiki/Naming_convention_(編程)#Java),它將幫助人們閱讀您的Java代碼(並且它將被正確突出顯示)。 –

+0

是的,這就是我的意思,我會再讀一遍。 – Bouji

回答

1

在控制器初始化,通過註釋它@FXML使變量訪問,並在控制器的initialize()初始化方法:

public class Controller { 
    private Button Next; //1st button 
    private Button J2inc; //2nd button 
    private Button J1inc; /3rd button 

    @FXML 
    private ImageView Img1; 

    private ImageView Img2; 

    public void initialize() { 
     Img1.setImage(new Image(...)); 
    } 

    void Inc2(ActionEvent event) { 
     //nothing for the moment 
    } 

    void Inc1(ActionEvent event) { 
     //nothing for the moment 
    } 

    void Nextimg(ActionEvent event) { 
     //nothing for the moment 
    } 
} 

如果你更喜歡直接在FXML初始化,提供了image屬性的值。在場景構建器中,您可以選擇ImageView,然後在右上角的「圖像」字段中鍵入圖像的URL(在「屬性」下)。請務必閱讀Image documentation瞭解如何解釋URL的字符串表示。

+0

它的工作原理,謝謝。 問題已解決。 – Bouji

+0

@Bouji如果問題是解決方案,你應該檢查答案是否正確。 – Sedrick