2017-07-18 78 views
0

我無法填充從場景生成器創建的我的JavaFX組合框。雖然我搜索了,但我找不到這個錯誤的修復。無法填充我的JavaFX組合框

下面的例子都不起作用。

@FXML ComboBox ComboStatus; 

@Override 
    public void initialize(URL url, ResourceBundle rbs) {   
     ComboStatus.getItems().addAll("Single","Married"); 
    } 

ObservableList<String> statusList = FXCollections. 
      observableArrayList(
        "Single", 
        "Married" 
    ); 

@FXML ComboBox<String> ComboStatus; 

@Override 
    public void initialize(URL url, ResourceBundle rbs) { 
     // TODO Auto-generated method stub 
     ComboStatus.setItems(statusList); 
    } 

幫助,將不勝感激。

+1

這兩個代碼片段是正確的:如果他們不工作,你會在某個地方出現其他問題。創建一個[MCVE]並將其發佈到您的問題中。 –

+1

你的fxml是什麼?你提供的代碼看起來是正確的。 –

+0

奇怪。如果您在該行上放置斷點並在調試模式下運行,程序是否會停在那裏?如果你然後執行該行,你會得到任何錯誤?像例如NullPointerExeption是否因爲FXML中的組合框名稱不同? BTW。我寧願使用comboStatus(在開始時使用小寫'c')比ComboStatus。 – tomorrow

回答

0

這裏的代碼,做工作的一個例子,希望幫助:

擴展類應用:

public class Test extends Application{ 

    public static void main(String[] args) { 
     Application.launch(Test.class, args); 
    } 

    @Override 
    public void start(Stage primaryStage) throws Exception { 
     FXMLLoader loader = new 
      FXMLLoader(Test.class.getResource("/test/MyExample.fxml")); 
     AnchorPane pane = (AnchorPane)loader.load(); 
     Scene scene = new Scene(pane); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 
} 

控制器類:

public class MyExampleController implements Initializable { 

    //I think the problem with your code was that you did not use 
    //ComboBox<String> 
    @FXML 
    private ComboBox<String> cbxStatus; 


    @Override 
    public void initialize(URL url, ResourceBundle rb) { 
     cbxStatus.getItems().addAll("Single", "Married"); 
     //you can make it so that an item is already selected 
     //instead of no item being selected until the user clicks on the box 
     //to select 
     cbxStatus.getSelectionModel().select(0); 
    }  

} 
+0

Thankyou,但如果你看看我的第二個例子,我確實使用。我已經解決了這個問題,正如我在上面的帖子的評論部分所說的那樣,通過製作一個「最小」或者所以他們稱之爲。不管怎麼說,還是要謝謝你。 –