2014-03-25 50 views
0

我對Java FX和場景構建器相當陌生。Java FX - 場景構建器 - 如何獲取表格的選定值

我有一個表視圖,充滿了來自我的數據庫中的數據來我得到了這個工作已經,這裏是代碼:

public class GridPaneController implements Initializable { 

// Table 
@FXML 
TableView<Box> table; 
@FXML 
TableColumn<Box, Integer> boxId; 
@FXML 
TableColumn<Box, String> name; 
@FXML 
TableColumn<Box, Integer> groesse; 
@FXML 
TableColumn<Box, String> einstreu; 
@FXML 
TableColumn<Box, Boolean> fenster; 
@FXML 
TableColumn<Box, String> standort; 
@FXML 
TableColumn<Box, Integer> tagessatz; 

ObservableList<Box> data = FXCollections.observableArrayList(); 

@Override 
public void initialize(URL location, ResourceBundle resources) { 
    boxId.setCellValueFactory(new PropertyValueFactory<Box, Integer>("boxId")); 
    name.setCellValueFactory(new PropertyValueFactory<Box, String>("name")); 
    groesse.setCellValueFactory(new PropertyValueFactory<Box, Integer>("groesse")); 
    einstreu.setCellValueFactory(new PropertyValueFactory<Box, String>("einstreu")); 
    fenster.setCellValueFactory(new PropertyValueFactory<Box, Boolean>("fenster")); 
    standort.setCellValueFactory(new PropertyValueFactory<Box, String>("standort")); 
    tagessatz.setCellValueFactory(new PropertyValueFactory<Box, Integer>("tagessatz")); 

    List<Box> boxen = serv.zeigeAlleBoxen();  
    for(Box b : boxen) { 
     data.add(b); 
    } 
    table.setItems(data); 
} 

}

我現在想做什麼:

我在我的場景中有一個「細節」部分,該部分應該顯示當前在此表中選擇的表項的詳細信息。我不知道的是如何將當前所選表項的值存入我的代碼中。

爲了讓多一點明確: 在我的細節部分,我有兩個標籤:

@FXML 
String label_name; 

@FXML 
String label_tagessatz; 

當我點擊一個特定的表項,label_namelabel_tagessatz應更新所點擊的價值表條目。我假設我應該定義一個在表視圖的onclick事件上調用的方法,但是如何獲取所選表項的值?

我想,甚至更好的方法來解決這個問題:我將不得不將標籤的textproperty綁定到選定的表格元素。現在我仍然需要知道如何得到這個。

回答

1
table.getSelectionModel().selectedItemProperty().addListener(
      (ObservableValue<? extends Box> ov, Box b, Box b1) -> { 
    label_name.textProperty().bind(b1.nameProperty()); 
}); 

您需要在Box類中有nameProperty()方法。