无法在JavaFX的数据添加到表(Can't add data to table in ja

2019-10-18 14:44发布

正如在下面的代码所示我试图一些数据I添加到表中。 但是,当我运行应用程序,只只显示空表。 什么是可能的原因这个问题?

package com.fg.transbridge.tool.ui;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

public class TableViewController implements Initializable {

    @FXML
    private TableColumn<Person, String> colX;
    @FXML
    private TableColumn<Person, String> colY;

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {

        final TableView<Person> table = new TableView<Person>();
        final ObservableList<Person> data = FXCollections.observableArrayList(new Person("Jacob", "Smith"), new Person("Isabella", "Johnson"), new Person("Ethan", "Williams"),
                new Person("Emma", "Jones"), new Person("Michael", "Brown"));

        colX.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));

        colY.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));

        table.setItems(data);
        table.getColumns().addAll(colX, colY);

    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

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

        }

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

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

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }

    }

}

FXML文件具有下面的代码和更多一些:

TableView.fxml

<TableView layoutX="172.0" layoutY="106.0" prefHeight="200.0" prefWidth="200.0">
      <columns>
        <TableColumn prefWidth="75.0" text="Column X" fx:id="colX" />
        <TableColumn prefWidth="75.0" text="Column Y" fx:id="colY"/>
      </columns>
    </TableView>

Answer 1:

您创建和发布数据的table ,从来没有在你的被引用FXML文件,并从未在节点图中可见。

你必须添加fx:id属性的TableView的元素:

<TableView fx:id= "table "layoutX="172.0" layoutY="106.0" prefHeight="200.0" prefWidth="200.0">

参考该表中的控制器

@FXML    
TableView<Person> table

除去final TableView<Person> table = new TableView<Person>();FXMLLoader将初始化为你的所有组件。

看到这个例子使用TableViewFXML



Answer 2:

你的问题很简单。 您创建一个新的TableView但科拉姆已经在你的FXML的tableview。 只要删除:

final TableView<Person> table = new TableView<Person>();

并添加

@FXML
private TableView table;


文章来源: Can't add data to table in javaFX