我创建了一个目录来保存文件(特别是excel和word文件)。我尝试将它添加到一个表中,但唯一显示的是一个可以“点击”的空白区域(尽管它没有做任何事情)。 我无法获得要在表格中显示的excel / word文件的名称。它显然能够检测目录中的文件,只是没有名称。 我还希望能够在表格中单击这些文件并让程序在此之后访问它们,所以我不知道是否可以使用字符串并将其添加到表中。
答案 0 :(得分:0)
一般情况下,您可以选择一行但无法看到任何内容,这意味着您添加了一个空字符串。另一种选择可能是您没有定义任何列。下面的代码显示了可以使用的表的示例。如果您发布代码也会有所帮助。
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
中。
很抱歉答案很长。希望它有所帮助!