2017-07-11 56 views
-1

我創建了一個目錄來保存文件(特別是excel和word文件)。我嘗試將它添加到表格中,但唯一顯示的是一個可以「點擊」的空白空間(儘管它沒有做任何事情)。 我無法獲取表格中顯示的excel/word文件的名稱。它顯然能夠檢測目錄中的文件,只是沒有名字。 我也希望能夠點擊表中的這些文件,然後讓程序訪問它們,所以我不知道是否可以使用字符串並將其添加到表中。如何在tableview中添加文件javafx

回答

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中。

對不起,很長的答案。希望它有幫助!