2015-10-01 34 views
2

我试过这段代码以获取组合框中选定的值,并且此代码有效。如何在表视图中获取在ComboBoxTableCell中选择的值

String cate = category.getValue().toString(); 

但如何在一个ComboBoxTableCellTableView得到选择的值?

使用下面的代码我得到一个ComboBox内表观统领选择在组合框中表格单元格中的表视图中

columnmain2.setCellFactory(ComboBoxTableCell.forTableColumn(names.toString())); 

,以及如何将价值观?

+1

如果事情按照通常的方式设置,当一个项目在组合框中选择,它会在该项目更新相应的属性表格行。因此,您只需查看表格的项目列表即可查看选定的值。 –

回答

3

当用户退出该组合框表格单元格的编辑模式时,您可以获取组合框选定值。即当新值被提交时。您需要使用tablecolumn.setOnEditCommit()方法。这是一个完整的可运行的代码示例(MCVE为ComboBoxTableCell演示):

public class ComboBoxTableCellDemo extends Application 
{ 
    private TableView<Person> table = new TableView<>(); 
    private final ObservableList<Person> data 
      = FXCollections.observableArrayList(
        new Person("Bishkek"), 
        new Person("Osh"), 
        new Person("New York"), 
        new Person("Madrid") 
      ); 

    @Override 
    public void start(Stage stage) 
    { 
     TableColumn<Person, String> cityCol = new TableColumn<>("City"); 
     cityCol.setMinWidth(200); 
     cityCol.setCellValueFactory(new PropertyValueFactory<>("city")); 
     cityCol.setCellFactory(ComboBoxTableCell.<Person, String>forTableColumn("Bishkek", "Osh", "New York", "Madrid")); 
     cityCol.setOnEditCommit((TableColumn.CellEditEvent<Person, String> e) -> 
     { 
      // new value coming from combobox 
      String newValue = e.getNewValue(); 

      // index of editing person in the tableview 
      int index = e.getTablePosition().getRow(); 

      // person currently being edited 
      Person person = (Person) e.getTableView().getItems().get(index); 

      // Now you have all necessary info, decide where to set new value 
      // to the person or not. 
      if (ok_to_go) 
      { 
       person.setCity(newValue); 
      } 
     }); 

     table.setItems(data); 
     table.getColumns().addAll(cityCol); 
     table.setEditable(true); 

     stage.setScene(new Scene(new VBox(table))); 
     stage.show(); 
    } 


    public static class Person 
    { 
     private String city; 

     private Person(String city) 
     { 
      this.city = city; 
     } 


     public String getCity() 
     { 
      return city; 
     } 


     public void setCity(String city) 
     { 
      System.out.println("city set to new value = " + city); 
      this.city = city; 
     } 
    } 


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

} 
+1

thanxx很多@UlukBiy !!!!它的工作原理,我也得到了价值当字符串newValue = e.getNewValue(); 。 – Seban

相关问题