JavaFX,对TableView中显示的数据的操作

时间:2016-09-23 08:40:41

标签: java javafx javafx-8

是否有可能从数据库中读取数据以在ObservableList TableView中显示它们进行迭代?我想在显示每一行操作之前进行。

1. operation on line 1
2. display line 1 in tableview
3. operation on line 2
4. display line 2 in tableview
... and so on.

一切都会在后台线程中发生(服务或任务?) 操作将搜索密钥的存在并分配值。

当在TableView中编辑数据时加载所有内容时,是否可以只替换线程中的一行,以免重载整个视图?对所有人来说,工作得很快。

1 个答案:

答案 0 :(得分:0)

我为你准备了一些代码,我希望这就是你所需要的。 一般的想法是你必须使用新线程并使用Task类。 在这里,您可以阅读更多相关信息:https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm

public class Main extends Application {
  private TableView<Person> table = new TableView<Person>();
  ArrayList<Person> listPerson = new ArrayList<>(); //this list can be filled from database
  private ObservableList<Person> data;

  public Main() {
    listPerson.add(new Person("Ania"));
    listPerson.add(new Person("Kasia"));
    listPerson.add(new Person("Monika"));
    listPerson.add(new Person("Jola"));
    listPerson.add(new Person("Ewa"));
    data = FXCollections.observableArrayList(listPerson);
  }


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

  @Override public void start(Stage stage) throws InterruptedException {

    TableColumn firstNameCol = new TableColumn("First Name");
    firstNameCol.setMinWidth(100);
    firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
    table.getColumns().addAll(firstNameCol);

    final VBox vbox = new VBox();
    vbox.getChildren().addAll(table);
    Scene scene = new Scene(vbox, 400, 400);
    stage.setScene(scene);
    stage.show();

    //Use new thread where you can proceed your data and add dynamically to the TableVIew
    Task<Void> task = new Task<Void>() {
      @Override protected Void call() throws Exception {
        for (Person person : listPerson) {
          System.out.println("Do something with person: " + person);
          synchronized (this) {
            this.wait(3000);
            table.getItems().add(person);
            System.out.println(person + " added to table. Do the next one \n");
          }
        }
        return null;
      }
    };

    Thread th = new Thread(task);
    th.setDaemon(true);
    th.start();
  }

  public class Person {
    private final SimpleStringProperty firstName;

    public Person(String fName) {
      this.firstName = new SimpleStringProperty(fName);
    }

    public String getFirstName() {
      return firstName.get();
    }

    public void setFirstName(String fName) {
      firstName.set(fName);
    }

    @Override public String toString() {
      return firstName.getValue();
    }
  }
}

就像这张图片一样:

enter image description here

相关问题