2015-07-03 3 views
0

Я извлекаю данные из XML-файла с помощью Wrapper для моего класса модели.Добавление индекса записей в столбец Javafx Tableview

Модель Класс:

private final StringProperty fileSubject; 
private final StringProperty fileDate; 
private final StringProperty fileRemarks; 

public void setFileSubject(String fileSubject){ 
    this.fileSubject.set(fileSubject); 
} 
public String getFileSubject() { 
    return fileSubject.get(); 
} 
public StringProperty fileSubjectProperty() { 
    return fileSubject; 
} 

public void setFileDate(String fileDate){ 
    this.fileDate.set(fileDate); 
} 
public String getFileDate() { 
    return fileDate.get(); 
} 
public StringProperty fileDateProperty() { 
    return fileDate; 
} 

public void setFileRemarks(String fileRemarks){ 
    this.fileRemarks.set(fileRemarks); 
} 
public String getFileRemarks() { 
    return fileRemarks.get(); 
} 
public StringProperty fileRemarksProperty(){ 
    return fileRemarks; 
} 

/** 
* Default constructor. 
*/ 
public FileModel(){ 
    this(null,null, null); 
} 

/** 
*Constructor with some initial data. 
* 
*@param 
* 
*/ 

public FileModel(String fileSubject, String fileDate, String fileRemarks){ 
    this.fileSubject = new SimpleStringProperty(fileSubject); 
    this.fileDate = new SimpleStringProperty(fileDate); 
    this.fileRemarks = new SimpleStringProperty(fileRemarks); 
} 

} 

Упаковочный Класс:

@XmlRootElement(name = "files") 
public class FileListWrapper { 

private List<FileModel> files; 

@XmlElement(name = "file") 
public List<FileModel> getFiles() { 
    return files; 
} 

public void setFiles(List<FileModel> files) { 
    this.files = files; 
} 

} 

Вот как я демаршаллизации его:

JAXBContext context = JAXBContext 
       .newInstance(FileListWrapper.class); 
Unmarshaller um = context.createUnmarshaller(); 
File file = new File("xxxxxxxxxx/xxx/x/xxxx/x.xml"); 
     // Reading XML from the file and unmarshalling. 
     FileListWrapper wrapper = (FileListWrapper) um.unmarshal(file); 
     fileData.clear(); 
     fileData.addAll(wrapper.getFiles()); 

Теперь я добавляю извлеченные данные в Tableview как ниже:

@FXML 
private void initialize(){ 
    //Initialize the file table with the three columns. 

    indexColumn = new TableColumn<>("Index"); 
    indexColumn.setCellFactory(col -> { 
     TableCell<FileModel, Void> cell = new TableCell<>(); 
     cell.textProperty().bind(Bindings.createStringBinding(() -> { 
      if (cell.isEmpty()) { 
       return null ; 
      } else { 
       return Integer.toString(cell.getIndex()); 
      } 
     })); 
     return cell ; 
    }); 

fileTable.getColumns().add(0, indexColumn); 

    fileSubjectColumn.setCellValueFactory(cellData -> cellData.getValue().fileSubjectProperty()); 
    fileDateColumn.setCellValueFactory(cellData -> cellData.getValue().fileDateProperty()); 

    fileTable.getSelectionModel().selectedItemProperty().addListener(
      (observable, oldValue, newValue) -> showFileDetails(newValue)); 
    showFileDetails(null); 

} 

/** 
*Is called by the main application to give a reference back to itself. 
* 
*@param mainApp 
*/ 
public void setMainApp(MainAppClass mainApp){ 
    this.mainApp = mainApp; 

    FilteredList<FileModel> filteredData = new FilteredList<>(mainApp.getFileData(), p -> true); 

    // 2. Set the filter Predicate whenever the filter changes. 
    filterField.textProperty().addListener((observable, oldValue, newValue) -> { 
     filteredData.setPredicate(files -> { 
      // If filter text is empty, display all files. 
      if (newValue == null || newValue.isEmpty()) { 
       return true; 
      } 

      // Compare File Subject and Date of every file with filter text. 
      String lowerCaseFilter = newValue.toLowerCase(); 
      if (files.getFileSubject().toLowerCase().indexOf(lowerCaseFilter) != -1) { 
       return true; // Filter matches Subject. 
      } 
       else if (files.getFileDate().toLowerCase().indexOf(lowerCaseFilter) != -1) { 
       return true; // Filter matches last name. 
      } 
      return false; // Does not match. 
     }); 
    }); 

    // 3. Wrap the FilteredList in a SortedList. 
    SortedList<FileModel> sortedData = new SortedList<>(filteredData); 

    // 4. Bind the SortedList comparator to the TableView comparator. 
    sortedData.comparatorProperty().bind(fileTable.comparatorProperty()); 

    // 5. Add sorted (and filtered) data to the table. 

    fileTable.setItems(sortedData); 

} 

Теперь, indexColumn не отображает ни одного указателя. Пожалуйста, помогите мне с этим. Я пробовал несколько вещей, но не работал.

ответ

1

Если я правильно понимаю, индекс является только индексом элемента в списке элементов таблицы. Таким образом, вы можете сделать

TableColumn<FileModel, Void> indexCol = new TableColumn<>("Index"); 
indexCol.setCellFactory(col -> { 
    TableCell<FileModel, Void> cell = new TableCell<>(); 
    cell.textProperty().bind(Bindings.createStringBinding(() -> { 
     if (cell.isEmpty()) { 
      return null ; 
     } else { 
      return Integer.toString(cell.getIndex()); 
     } 
    }, cell.emptyProperty(), cell.indexProperty())); 
    return cell ; 
}); 

Полного примера (с использованием стандартного Oracle учебника примера):

import java.util.function.Function; 

import javafx.application.Application; 
import javafx.beans.binding.Bindings; 
import javafx.beans.binding.StringBinding; 
import javafx.beans.property.SimpleStringProperty; 
import javafx.beans.property.StringProperty; 
import javafx.beans.value.ObservableValue; 
import javafx.collections.ListChangeListener.Change; 
import javafx.scene.Scene; 
import javafx.scene.control.TableCell; 
import javafx.scene.control.TableColumn; 
import javafx.scene.control.TableView; 
import javafx.scene.layout.BorderPane; 
import javafx.stage.Stage; 

public class TableViewWithIndexColumn extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     TableView<Person> table = new TableView<>(); 
     table.setEditable(true); 

     table.getItems().addAll(
       new Person("Jacob", "Smith", "[email protected]"), 
       new Person("Isabella", "Johnson", 
         "[email protected]"), 
       new Person("Ethan", "Williams", "[email protected]"), 
       new Person("Emma", "Jones", "[email protected]"), 
       new Person("Michael", "Brown", "[email protected]")); 



     TableColumn<Person, String> firstNameCol = createColumn("First Name", 
       Person::firstNameProperty, 150); 
     TableColumn<Person, String> lastNameCol = createColumn("Last Name", 
       Person::lastNameProperty, 150); 
     TableColumn<Person, String> emailCol = createColumn("Email", 
       Person::emailProperty, 150); 

     // index column doesn't even need data... 
     TableColumn<Person, Void> indexCol = new TableColumn<>("Index"); 
     indexCol.setPrefWidth(50); 

     // cell factory to display the index: 
     indexCol.setCellFactory(col -> { 

      // just a default table cell: 
      TableCell<Person, Void> cell = new TableCell<>(); 

      cell.textProperty().bind(Bindings.createStringBinding(() -> { 
       if (cell.isEmpty()) { 
        return null ; 
       } else { 
        return Integer.toString(cell.getIndex()); 
       } 
      }, cell.emptyProperty(), cell.indexProperty())); 

      return cell ; 
     }); 

     table.getColumns().add(indexCol); 
     table.getColumns().add(firstNameCol); 
     table.getColumns().add(lastNameCol); 
     table.getColumns().add(emailCol); 

     primaryStage.setScene(new Scene(new BorderPane(table), 600, 400)); 
     primaryStage.show(); 
    } 

    private <S, T> TableColumn<S, T> createColumn(String title, 
      Function<S, ObservableValue<T>> property, double width) { 
     TableColumn<S, T> col = new TableColumn<>(title); 
     col.setCellValueFactory(cellData -> property.apply(cellData.getValue())); 
     col.setPrefWidth(width); 
     return col; 
    } 

    public static class Person { 
     private final StringProperty firstName = new SimpleStringProperty(); 
     private final StringProperty lastName = new SimpleStringProperty(); 
     private final StringProperty email = new SimpleStringProperty(); 

     public Person() { 
      this("", "", ""); 
     } 

     public Person(String firstName, String lastName, String email) { 
      setFirstName(firstName); 
      setLastName(lastName); 
      setEmail(email); 
     } 

     public final StringProperty firstNameProperty() { 
      return this.firstName; 
     } 

     public final java.lang.String getFirstName() { 
      return this.firstNameProperty().get(); 
     } 

     public final void setFirstName(final java.lang.String firstName) { 
      this.firstNameProperty().set(firstName); 
     } 

     public final StringProperty lastNameProperty() { 
      return this.lastName; 
     } 

     public final java.lang.String getLastName() { 
      return this.lastNameProperty().get(); 
     } 

     public final void setLastName(final java.lang.String lastName) { 
      this.lastNameProperty().set(lastName); 
     } 

     public final StringProperty emailProperty() { 
      return this.email; 
     } 

     public final java.lang.String getEmail() { 
      return this.emailProperty().get(); 
     } 

     public final void setEmail(final java.lang.String email) { 
      this.emailProperty().set(email); 
     } 

    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
+0

Ен !!! он не отображает данные в столбце и даже не создает столбец с именем «Индекс». – user3626720

+0

Это образец моего кода: [link] (http://code.makery.ch/library/javafx-8-tutorial/part5/) @James_D – user3626720

+0

Не могу проверить это прямо сейчас, но я предполагаю, что вы добавили столбец к таблице ...? –

Смежные вопросы