从从 SQL 语句填充的数组列表中填充组合框

Ann*_*nna 1 eclipse combobox javafx

我正在尝试使用由 SQL 语句填充的列表填充 ComboBox。

我试过这个:

public void buildData(){        
  ObservableList<ComboBox>  data = FXCollections.observableArrayList();

  Connection conn = db.makeConnection();
    try{      
        String SQL = "Select Feature from FeaturesTable Order By Feature";            
        ResultSet rs = conn.createStatement().executeQuery(SQL);  
        while(rs.next()){
            ComboBox cb = new ComboBox();
            cb.featureCombo.set(rs.getString("Feature"));                       

            featureCombo.add(cb);                  
        }
        featureCombo.setItems(data);
    }
    catch(Exception e){
          e.printStackTrace();
          System.out.println("Error on Building Data");            
    }
}
Run Code Online (Sandbox Code Playgroud)

我在 cb.featureCombo.set 下收到错误“featureCombo 无法解析或不是字段”,但 featureCombo 存在为:

@FXML
private ObservableList<ComboBox> featureCombo;
Run Code Online (Sandbox Code Playgroud)

然后在 featureCombo.setItems(data) 下出现另一个错误;可能是因为同样的问题。

如果有人有更好的方法来做到这一点,我不会采用这种方法。

cha*_*cea 5

如果你想要一个名为featureCombo组合框,你将不得不宣布它作为一个组合框,而不是作为private ObservableList<ComboBox> featureCombo;其制造ObservableList

就像是

@FXML
ComboBox<String> featureCombo;
Run Code Online (Sandbox Code Playgroud)

然后在你的方法中,你需要制作一个列表String来填充 ComboBox(你目前有一个 ComboBox 列表)

public void buildData(){        
  ObservableList<String>  data = FXCollections.observableArrayList(); //List of String

  Connection conn = db.makeConnection();
    try{      
        String SQL = "Select Feature from FeaturesTable Order By Feature";            
        ResultSet rs = conn.createStatement().executeQuery(SQL);  
        while(rs.next()){
            data.add(rs.getString("Feature")); //add the String to the list                                     
        }
        featureCombo.setItems(data); //Set the list of String as the data for your combo box
    }
    catch(Exception e){
          e.printStackTrace();
          System.out.println("Error on Building Data");            
    }
}
Run Code Online (Sandbox Code Playgroud)