一般来说,您可以选择一行但看不到任何内容,这意味着您添加了一个空字符串。另一种选择可能是您没有定义任何列。下面的代码显示了可以使用的表格示例。如果您发布代码也会有所帮助。
private TableView<FileWrapper> createTable(){
//Create a new table view which contains File instances
TableView<FileWrapper> fileView = new TableView<FileWrapper>();
//create the column which displays the file name - a string.
TableColumn<FileWrapper, String> nameCol = new TableColumn<FileWrapper, String>();
//setting the text which indicates the column name
nameCol.setText("Name");
//defining the the values of this column are in a method called 'nameProperty' in our File class
//the method needs to return a ReadOnlyStringProperty which contains the value to show.
nameCol.setCellValueFactory(new PropertyValueFactory<FileWrapper, String>("name"));
fileView.getColumns().add(nameCol);
//Add your files to the table...
return fileView; //returning the table so it can be used in our scene
}
//A wrapper for files in your table
public static class FileWrapper{
private File file;//holds the file object
private SimpleStringProperty name;//a property for the name of the file
FileWrapper(File file){
name = new SimpleStringProperty();
name.set(file.getName());
this.file = file;
}
//this method returns the property of the name and is used by the table to chose the value of
//the column using it.
public SimpleStringProperty nameProperty(){
return name;
}
public String getPath(){
return path;
}
}
所以我们创建了一个表视图,它指向一个类,该类包含每个文件的名称和File 对象。然后,我们为名称创建一个列,并定义它的值来自类的nameProperty 方法。我们可以将该列添加到表中并添加我们想要的任何文件。
当我使用表格选择要打开的内容时,我使用一个按钮,当按下它时,我会得到选定的行 table.getSelectionModel().getSelectedItem() 并相应地打开我需要的内容。
另一方面,您可能想改用ListView,因为您似乎只需要一列,因此表是无用的。下面的代码展示了一个使用ListView的例子:
private ListView<FileWrapper> createList(){
//create a list for FileWrapper class
//this time, the value used to show stuff is the value from toString of
//the class
ListView<FileWrapper> fileView = new ListView<FileWrapper>();
//Add your files to the table...
return fileView;//return the list so it can be used in our scene
}
//A wrapper for files in your table
public static class FileWrapper{
private File file;//holds the file object
private String name;//the name of the file
FileWrapper(File file){
name = file.getName();
this.file = file;
}
public File getFile(){
return file;
}
//this will be the value used by the list view and shown to the user
@Override
public String toString() {
return name;
}
}
与以前不同,这里我们不需要列,显示的值是从类的toString 接收的。所以我们定义了一个String变量来保存名字,并在类的toString中返回。
抱歉,答案很长。希望对您有所帮助!