2016-01-02 79 views
1

我想創建一個令人難以置信的簡單的JavaFX TableView:1字符串。我有我想可視化陣列:*基本*單字符串列的JavaFX TableView

String[] acronyms = {"Foo", "Bar"}; 

documentation假定一些數據類型來填充多個列(例如人,書籍,等等)。我比「hello world」要多得多:只顯示一個字符串數組。

使用場景建設者我創建了一個FXML文件與表格&列:

<TableView fx:id="clientAcronymTable" prefHeight="200.0" prefWidth="200.0"> 
<columns> 
    <TableColumn fx:id="clientAcronymColumn" prefWidth="199.0" text="Client Acronyms" /> 
</columns> 
    <columnResizePolicy> 
    <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" /> 
    </columnResizePolicy> 
</TableView> 

我再「線」,這些元素在我的控制器:

@FXML private TableView<String> clientAcronymTable; 

@FXML private TableColumn<ObservableList<String>, String> clientAcronymColumn; 

而且我Initializable::initialize方法我裏面有:

clientAcronymTable.setItems(FXCollections.observableList(acronyms)); 

但是,沒有一個字符串a在GUI中ppear。我知道正在發生,因爲在列中顯示可見的行線,但它們都是空的。

有不真正適用的過程中類似的問題:

  1. Related to more than one column, not applicable
  2. Creates a custom Row Class which seems like overkill

所以,我的問題是:

如何使我的數組中的字符串可見於TableView內部

如何讓單列可編輯,以便用戶可以添加更多字符串

預先感謝您的考慮和迴應。

+1

你應該使用cellvaluefactory對於t他的 –

回答

3

首先,您的TableColumn類型錯誤。由於每個行包含一個String(不是ObservableList<String>),你需要

@FXML private TableColumn<String, String> clientAcronymColumn; 

然後你需要一個cellValueFactory,它告訴每一個細胞中列如何得到它從該行顯示值:

clientAcronymColumn.setCellValueFactory(cellData -> 
    new ReadOnlyStringWrapper(cellData.getValue())); 

至於添加更多的字符串,你通常有一個外部的文本字段爲用戶提供更多:

// you can of course define the text field in FXML if you prefer... 
TextField newAcronymTextField = new TextField(); 

newAcronymTextField.setOnAction(e -> { 
    clientAcronymTable.getItems().add(newAcronymTextField.getText()); 
    newAcronymTextField.clear(); 
}); 
+0

你知道'cellData'的類型是什麼嗎? –

+0

'cellData'是一個'TableColumn.CellDataFeatures ' –

+0

您的解決方案有效。謝謝。 –