使用字符串填充tableview [英] Populating a tableview with strings

查看:132
本文介绍了使用字符串填充tableview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了API和示例,但我无法理解如何填充tableview。

I have read the API and examples, but am unable to understand how to populate a tableview.

让我们说我有一个两列的String数组(String [ ] [])名称,价值 - 对。我现在只想创建一个tableview,它显示两列中的数据,在第一列中显示名称,在第二列中显示原始数组中所有行的值。

Let us say I have a two column String array (String[][]) with "name, value"-pairs. I now simply want to create a tableview which shows the data in two columns, displaying the name in the first and value in the second column for all the rows in the original array.

我尝试了什么?没什么,但似乎你需要创建observablelists,每列一个,将它绑定到各自的列,然后将列添加到tableview。但这涉及我所见过的所有例子中的工厂,这对我来说是一个外星人的概念。

What have I tried? Nothing, but it seems that you need to create observablelists, one for each column, bind it to its respective column and then add the column to the tableview. But this involves "factories" in all the examples I have seen which is an alien concept to me.

我猜这很简单,但我无法把头包住。请帮忙。

I'm guessing this is simple, but I'm unable to wrap my head around it. Please help.

推荐答案

单元格值工厂



对于每一列您的表格,您设置/创建单元格值工厂。每行在 tableview.getItems()中都有一个对应的对象。要确定此对象在列中的显示方式,每列都使用自己的Cell Value Factory。工厂接收对象并返回要显示的值。

Cell Value Factory

For each column in your table, you set/create a Cell Value Factory. Each row has a corresponding object in tableview.getItems(). To determine how this object is displayed across the columns, each column uses its own Cell Value Factory. The factories take in the object and return the value to be displayed.

因为 String [] [] 是一个 String [] 的数组,我们希望工厂接收 String [] 并返回 String 对应于其列。

Since String[][] is an array of String[]'s, we want the factories to take in a String[] and return the String corresponding to its column.

这是以这种方式创建Cell Value Factories的示例。它有点冗长,但可以用lambdas清理! (参见Lambdas部分)。

Here is an example of creating the Cell Value Factories in this way. It is a little verbose but that can be cleaned up with lambdas! (see Lambdas section).

// ---------------------------------------Initialize the data
String[][] data = ...; // Get name/value pairs from somewhere

// ---------------------------------------Setup a TableView with two TableColumns 
    /* ... Code ... */

// ---------------------------------------Add Cell Value Factories
nameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String[], String>, ObservableValue<String>>() {
    @Override
    public ObservableValue<String> call(TableColumn.CellDataFeatures<String[], String> p) {
        String[] x = p.getValue();
        if (x != null && x.length>0) {
            return new SimpleStringProperty(x[0]);
        } else {
            return new SimpleStringProperty("<no name>");
        }
    }
});

valueColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String[], String>, ObservableValue<String>>() {
    @Override
    public ObservableValue<String> call(TableColumn.CellDataFeatures<String[], String> p) {
        String[] x = p.getValue();
        if (x != null && x.length>1) {
            return new SimpleStringProperty(x[1]);
        } else {
            return new SimpleStringProperty("<no value>");
        }
    }
});

// ---------------------------------------Add Data to TableView
tableView.getItems().addAll(Arrays.asList(data));



结果



如果你抛出这个例子(通过源代码),在舞台上,这就是你得到的。

Result

If you throw this example (via the Source Code), on a Stage, this is what you get.

Java有点儿详细,尤其是在玩匿名课程时。值得庆幸的是有lambdas,它给Java带来了一点可读性。以下是与示例相同的Cell Value Factories,用lambdas重写。

Java is a little verbose, especially when playing with anonymous classes. Thankfully there are lambdas, which bring a little readability back to Java. Here are the same Cell Value Factories from the example, re-written with lambdas.

nameColumn.setCellValueFactory((p)->{
        String[] x = p.getValue();
        return new SimpleStringProperty(x != null && x.length>0 ? x[0] : "<no name>");
});

valueColumn.setCellValueFactory((p)->{
        String[] x = p.getValue();
        return new SimpleStringProperty(x != null && x.length>1 ? x[1] : "<no value>");
});






源代码

这是一个独立的JavaFX类,它以这种方式使用Cell Value Factories。

Here is a stand-alone JavaFX class that uses Cell Value Factories in this way.

import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 *
 * @author nonfrt
 */
public class TableStuff extends Application {

    @Override
    public void start(Stage primaryStage) {

        // Create the data structure
        String[][] data = new String[5][2];
        data[0] = new String[]{"Jon Skeet","876k"};
        data[1] = new String[]{"Darin Dimitrov","670k"};
        data[2] = new String[]{"BalusC","660k"};
        data[3] = new String[]{"Hans Passant","635k"};
        data[4] = new String[]{"Marc Gravell","610k"};

        // Create the table and columns
        TableView<String[]> tv = new TableView();
            TableColumn<String[],String> nameColumn = new TableColumn();
                nameColumn.setText("Name Column");

            TableColumn<String[],String> valueColumn = new TableColumn();
                valueColumn.setText("Value Column");
        tv.getColumns().addAll(nameColumn,valueColumn);

        // Add cell value factories
//        nameColumn.setCellValueFactory((p)->{
//                String[] x = p.getValue();
//                return new SimpleStringProperty(x != null && x.length>0 ? x[0] : "<no name>");
//        });
//
//        valueColumn.setCellValueFactory((p)->{
//                String[] x = p.getValue();
//                return new SimpleStringProperty(x != null && x.length>1 ? x[1] : "<no value>");
//        });
        nameColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String[], String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<String[], String> p) {
                String[] x = p.getValue();
                if (x != null && x.length>0) {
                    return new SimpleStringProperty(x[0]);
                } else {
                    return new SimpleStringProperty("<no name>");
                }
            }
        });

        valueColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String[], String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<String[], String> p) {
                String[] x = p.getValue();
                if (x != null && x.length>1) {
                    return new SimpleStringProperty(x[1]);
                } else {
                    return new SimpleStringProperty("<no value>");
                }
            }
        });

        // Add Data
        tv.getItems().addAll(Arrays.asList(data));

        // Finish setting the stage
        StackPane root = new StackPane();
        root.getChildren().add(tv);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Cell Value Factory Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

[注意: 回答 其他StackOverFlow问题就是另一个例子。 ]

[NOTE: The answer to this other StackOverFlow question is another example of this. ]

这篇关于使用字符串填充tableview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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