java 在 JavaFX 中填充 TableView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16911647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:22:22  来源:igfitidea点击:

Populating TableView in JavaFX

javaclassjavafx-2javafx

提问by user2282225

I am a newbie in here, my Table View in JavFX namely as tblStudent is NOT containing the
records that I want. How to do this, please help me.

我是这里的新手,我在 JavFX 中的表视图即 tblStudent 不包含
我想要的记录。如何做到这一点,请帮助我。

    public void populateData(){
      Connection c ;
      data = FXCollections.observableArrayList();
      try{
        c = ConnectionClass.connect();
        //SQL FOR SELECTING ALL OF CUSTOMER
        String SQL = "SELECT * FROM `student`";
        //ResultSet
        ResultSet rs = c.createStatement().executeQuery(SQL);


        studentIDCol = new TableColumn("Student ID");
        nameCol = new TableColumn("Name");
        addressCol = new TableColumn("Address");
        ageCol = new TableColumn("Age");
        contactnoCol = new TableColumn("Contact Number");

        while(rs.next()){
            //Iterate Row
            ObservableList<String> row = FXCollections.observableArrayList();

            row.add(rs.getString("id"));
            row.add(rs.getString("name"));
            row.add(rs.getString("address"));
            row.add(rs.getString("age"));
            row.add(rs.getString("contact_num"));

            System.out.println("Row [1] added "+row );
            data.add(row);

        }

        //FINALLY ADDED TO TableView
        tblStudent.getItems().setAll(data);
      }catch(Exception e){
          e.printStackTrace();
          System.out.println("Error on Building Data");             
      }
 }

Anyone who knows this?

有谁知道这个吗?

回答by Antonio J.

You need to set the cell value factory to all your columns like this:

您需要像这样将单元格值工厂设置为所有列:

TableColumn<ObservableList<String>, String> studentIDCol  = new TableColumn<>("Student ID");
    studentIDCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {         
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(0));
        }
    });

And also I recommend you to extract your query to a service, because the query will block the JavaFX Thread. Check out http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm

而且我还建议您将查询提取到服务中,因为该查询会阻塞 JavaFX 线程。查看http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm

Check this full example with test data.

用测试数据检查这个完整的例子。

public void start(Stage stage) throws Exception {
    VBox vbox = new VBox(10.0);
    vbox.setAlignment(Pos.CENTER);

    final TableView<ObservableList<String>> table = new TableView<>();

    TableColumn<ObservableList<String>, String> studentIDCol  = new TableColumn<>("Student ID");
    studentIDCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {         
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(0));
        }
    }); 

    TableColumn<ObservableList<String>, String> nameCol = new TableColumn<>("Name");
    nameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {          
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(1));
        }
    });     

    TableColumn<ObservableList<String>, String> addressCol  = new TableColumn<>("Address");
    addressCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {           
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(2));
        }
    });     

    TableColumn<ObservableList<String>, String> ageCol  = new TableColumn<>("Age");
    ageCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {           
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(3));
        }
    });     

    TableColumn<ObservableList<String>, String> contactnoCol  = new TableColumn<>("Contact Number");
    contactnoCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {         
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(4));
        }
    });     

    table.getColumns().add(studentIDCol);
    table.getColumns().add(nameCol);
    table.getColumns().add(addressCol);
    table.getColumns().add(ageCol);
    table.getColumns().add(contactnoCol);   

    final ProgressBar bar = new ProgressBar(-1);
    bar.setVisible(false);

    final Button button = new Button("Fill");
    button.setOnAction(new EventHandler<ActionEvent>() {            
        @Override
        public void handle(ActionEvent event) {
            final Service<ObservableList<ObservableList<String>>> service = new Service<ObservableList<ObservableList<String>>>() {                 
                @Override
                protected Task<ObservableList<ObservableList<String>>> createTask() {
                    return new Task<ObservableList<ObservableList<String>>>() {
                        @Override
                        protected ObservableList<ObservableList<String>> call() throws Exception {
                            ObservableList<ObservableList<String>> items = FXCollections.observableArrayList();
                            items.add(FXCollections.observableArrayList("1", "2", "3", "4", "5"));
                            items.add(FXCollections.observableArrayList("1", "2", "3", "4", "5"));
                            items.add(FXCollections.observableArrayList("1", "2", "3", "4", "5"));
                            //Here the code for the query
                            Thread.sleep(5000);//To see the progress
                            return items;
                        }
                    };
                }
            };

            bar.visibleProperty().bind(service.runningProperty());
            button.disableProperty().bind(service.runningProperty());
            table.itemsProperty().bind(service.valueProperty());

            service.start();
        }
    });     

    vbox.getChildren().addAll(table, button, bar);
    Scene scene = new Scene(vbox, 300, 300);
    stage.setScene(scene);
    stage.show();
}

If you are using a FXML file. You need to skip the initialization step of the TableColumn.

如果您使用的是 FXML 文件。您需要跳过 TableColumn 的初始化步骤。

Declare the TableColumn as a fields in the file in your controller class with the @FXML annotation. Ensure you implements javafx.fxml.Initializable. And in the initialize method you can do the configuration side for every column. And avoid the add of the columns to the table, because they already are in the table view.

使用 @FXML 注释将 TableColumn 声明为控制器类中文件中的字段。确保您实现了 javafx.fxml.Initializable。在 initialize 方法中,您可以为每一列进行配置。并避免将列添加到表中,因为它们已经在表视图中。

Here is a sample if your are defining your TableView in your FXML like this:

如果您像这样在 FXML 中定义 TableView,这里是一个示例:

<TableView layoutX="145.0" layoutY="76.0" prefHeight="200.0" prefWidth="200.0">
  <columns>
    <TableColumn prefWidth="75.0" text="Student ID" fx:id="studentIDCol" />
    <TableColumn prefWidth="75.0" text="Name" fx:id="nameCol" />
    <TableColumn prefWidth="75.0" text="Address" fx:id="addressCol" />
    <TableColumn prefWidth="75.0" text="Age" fx:id="ageCol" />
  </columns>
</TableView>

Then your controller class will be like this:

那么你的控制器类将是这样的:

class YourTest implements javafx.fxml.Initializable{
//More Code
@FXML
TableColumn<ObservableList<String>, String> studentIDCol;
@FXML
TableColumn<ObservableList<String>, String> nameCol;
@FXML
TableColumn<ObservableList<String>, String> addressCol;
@FXML
TableColumn<ObservableList<String>, String> ageCol;
//More of your code 
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
    studentIDCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {         
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(0));
        }
    }); 

    nameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {          
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(1));
        }
    });             

    addressCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {           
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(2));
        }
    });     

    ageCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {           
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(3));
        }
    });     

    contactnoCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>() {         
        @Override
        public ObservableValue<String> call(CellDataFeatures<ObservableList<String>, String> cdf) {     
            return new SimpleStringProperty(cdf.getValue().get(4));
        }
    });  
}
//More of your Code
}

Hope it helps.

希望能帮助到你。