SimpleStringProperty和SimpleIntegerProperty TableView JavaFX [英] SimpleStringProperty and SimpleIntegerProperty TableView JavaFX

查看:480
本文介绍了SimpleStringProperty和SimpleIntegerProperty TableView JavaFX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试学习如何使用JavaFx Tableview,并且我在本教程中进行了简化:

So i am trying to learn how to use JavaFx Tableview and i stumpled across this tutorial:

Oracle tableview教程

在本教程中他们展示了为了填写你的tableView你必须用字符串填充它,但不只是你要格式化的任何字符串字符串 SimpleStringProperty

in this tutorial they show that in order to fill you tableView you have to fill it with Strings, but not just any String you have to format you String to a SimpleStringProperty

我尝试了没有格式,结果是没有任何信息显示!

i tried without the format and the result was that none of the information would show!

另外我发现如果要向表中添加 Integer ,则必须将其声明为 SimpleIntegerProperty

Also i found that if you want to add an Integer to the table you would have to declare it as an SimpleIntegerProperty

现在我对JavaFx还不熟悉,但这是否意味着当我创建一个对象时,我必须格式化所有的整数和字符串才能填充我的TableView?它似乎相当愚蠢,但也许有更高的目的?还是有办法避免它?

Now i am fairly new to JavaFx but does this mean that when i create an object i have to format all my Integers and Strings to be able to fill my TableView? it seems rather stupid but maybe there is a higher purpose? or is there a way to avoid it?

推荐答案

您不需要在表数据对象中使用属性来显示它们,尽管在某些情况下使用属性希望。

You don't need to use Properties in your table data objects for them to display, although use of Properties in certain circumstances is desirable.

以下代码将显示一个基于Person类的人员表,其中只有String字段。

The following code will display a table of people based on a Person class which has only String fields.

import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class ReadOnlyTableView extends Application {
  private TableView<Person> table = new TableView<Person>();
  private final ObservableList<Person> data =
    FXCollections.observableArrayList(
      new Person("Jacob", "Smith", "jacob.smith@example.com"),
      new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
      new Person("Ethan", "Williams", "ethan.williams@example.com"),
      new Person("Emma", "Jones", "emma.jones@example.com"),
      new Person("Michael", "Brown", "michael.brown@example.com")
    );

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

  @Override public void start(Stage stage) {
    stage.setTitle("Table View Sample");
    stage.setWidth(450);
    stage.setHeight(500);

    final Label label = new Label("Address Book");
    label.setFont(new Font("Arial", 20));

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

    TableColumn lastNameCol = new TableColumn("Last Name");
    lastNameCol.setMinWidth(100);
    lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));

    TableColumn emailCol = new TableColumn("Email");
    emailCol.setMinWidth(200);
    emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));

    table.setItems(data);
    table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

    final VBox vbox = new VBox();
    vbox.setSpacing(5);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(label, table);

    stage.setScene(new Scene(new Group(vbox)));
    stage.show();
  }

  public static class Person {
    private String firstName;
    private String lastName;
    private String email;

    private Person(String fName, String lName, String email) {
      this.firstName = fName;
      this.lastName = lName;
      this.email = email;
    }

    public String getFirstName() { return firstName; }
    public void setFirstName(String fName) { firstName = fName; }
    public String getLastName() { return lastName; }
    public void setLastName(String lName) { lastName = lName; }
    public String getEmail() { return email; }
    public void setEmail(String inMail) { email = inMail; }
  }
}

解释

使用Properties和ObservableLists的目的是这些是可听元素。使用属性时,如果datamodel中属性属性的值发生更改,则TableView中项的视图将自动更新以匹配更新的datamodel值。例如,如果某人的电子邮件属性的值设置为新值,则该更新将反映在TableView中,因为它会侦听属性更改。相反,如果使用普通字符串来表示电子邮件,则TableView将不会刷新,因为它不会意识到电子邮件值的更改。

The purpose of using Properties and ObservableLists is that these are listenable elements. When properties are used, if the value of a property attribute in the datamodel changes, the view of the item in the TableView is automatically updated to match the updated datamodel value. For example, if the value of a person's email property is set to a new value, that update will be reflected in the TableView because it listens for the property change. If instead, a plain String had been used to represent the email, the TableView would not refresh as it would be unaware of email value changes.

PropertyValueFactory 文档详细描述了这个过程:

The PropertyValueFactory documentation describes this process in detail:


如何使用此类的示例如下:

An example of how to use this class is:

TableColumn<Person,String> firstNameCol = new TableColumn<Person,String>("First Name");
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person,String>("firstName"));  

在此示例中,firstName字符串用作对
假设的引用Person类类型中的firstNameProperty()方法(这是
TableView项列表的类类型)。此外,此方法
必须返回一个Property实例。如果找到满足这些
要求的方法,则使用此
ObservableValue填充TableCell。此外,TableView将自动向返回的值添加
观察者,这样任何触发的更改都将由TableView观察到
,从而导致单元格立即更新。

In this example, the "firstName" string is used as a reference to an assumed firstNameProperty() method in the Person class type (which is the class type of the TableView items list). Additionally, this method must return a Property instance. If a method meeting these requirements is found, then the TableCell is populated with this ObservableValue. In addition, the TableView will automatically add an observer to the returned value, such that any changes fired will be observed by the TableView, resulting in the cell immediately updating.

如果不存在与此模式匹配的方法,则尝试调用get()或is()(
是getFirstName()或isFirstName)时会出现
支持。 )在上面的例子中)。如果存在与此模式匹配的方法
,则此方法返回的值为
,包装在ReadOnlyObjectWrapper中并返回给TableCell。
但是,在这种情况下,这意味着TableCell将不会是
能够观察ObservableValue的变化(如上面的
第一种方法中的情况)。

If no method matching this pattern exists, there is fall-through support for attempting to call get() or is() (that is, getFirstName() or isFirstName() in the example above). If a method matching this pattern exists, the value returned from this method is wrapped in a ReadOnlyObjectWrapper and returned to the TableCell. However, in this situation, this means that the TableCell will not be able to observe the ObservableValue for changes (as is the case in the first approach above).

更新

这是第一个例子的对比示例它演示了TableView如何根据对项目的ObservableList的更改以及对基于属性的项属性的值的更改来观察和自动刷新。

Here is a contrasting example to the first example which demonstrates how a TableView can observe and automatically refresh based on changes to it's ObservableList of items and changes to the value of a property based item attribute.

import javafx.application.Application;
import javafx.beans.property.*;
import javafx.collections.*;
import javafx.event.*;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class PropertyBasedTableView extends Application {
  private TableView<Person> table = new TableView<Person>();
  private final ObservableList<Person> data = FXCollections.observableArrayList();
  private void initData() {
    data.setAll(
      new Person("Jacob", "Smith", "jacob.smith@example.com"),
      new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
      new Person("Ethan", "Williams", "ethan.williams@example.com"),
      new Person("Emma", "Jones", "emma.jones@example.com"),
      new Person("Michael", "Brown", "michael.brown@example.com")
    );
  }

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

  @Override public void start(Stage stage) {
    initData();

    stage.setTitle("Table View Sample");
    stage.setWidth(450);
    stage.setHeight(500);

    final Label label = new Label("Address Book");
    label.setFont(new Font("Arial", 20));

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

    TableColumn lastNameCol = new TableColumn("Last Name");
    lastNameCol.setMinWidth(100);
    lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));

    TableColumn emailCol = new TableColumn("Email");
    emailCol.setMinWidth(200);
    emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));

    table.setItems(data);
    table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
    table.setPrefHeight(300);

    final Button setEmailButton = new Button("Set first email in table to wizard@frobozz.com");
    setEmailButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        if (data.size() > 0) {
          data.get(0).setEmail("wizard@frobozz.com");
        }  
      }
    });

    final Button removeRowButton = new Button("Remove first row from the table");
    removeRowButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        if (data.size() > 0) {
          data.remove(0);
        }  
      }
    });

    final Button resetButton = new Button("Reset table data");
    resetButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        initData();
      }
    });

    final VBox vbox = new VBox(10);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(label, table, setEmailButton, removeRowButton, resetButton);

    stage.setScene(new Scene(new Group(vbox)));
    stage.show();
  }

  public static class Person {
    private final StringProperty firstName;
    private final StringProperty lastName;
    private final StringProperty email;

    private Person(String fName, String lName, String email) {
      this.firstName = new SimpleStringProperty(fName);
      this.lastName = new SimpleStringProperty(lName);
      this.email = new SimpleStringProperty(email);
    }

    public String getFirstName() { return firstName.get(); }
    public void setFirstName(String fName) { firstName.set(fName); }
    public StringProperty firstNameProperty() { return firstName; }
    public String getLastName() { return lastName.get(); }
    public void setLastName(String lName) { lastName.set(lName); }
    public StringProperty lastNameProperty() { return lastName; }
    public String getEmail() { return email.get(); }
    public void setEmail(String inMail) { email.set(inMail); }
    public StringProperty emailProperty() { return email; }  // if this method is commented out then the tableview will not refresh when the email is set.
  }
}

这篇关于SimpleStringProperty和SimpleIntegerProperty TableView JavaFX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆