如何在 JavaFX 表视图中添加按钮 [英] How to add button in JavaFX table view

查看:68
本文介绍了如何在 JavaFX 表视图中添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谷歌和 Stackoverflow 上搜索过这个,但我没有得到给定的例子.有人可以向我解释一下吗.

I have searched at Google and Stackoverflow for this and I just don't get the given examples. Can someone please explain it to me.

我想向表格视图的最后一列添加一个按钮,当它被点击时,它应该触发一个监听器并传递按钮行的对象.我只是没有从 gist.github.com 中得到以下示例:

I want to add a button to the last column of a table view and when it gets clicked it should trigger a listener and pass the object of the buttons row. I just do not get the following example from gist.github.com:

这是我当前的完整代码:

This is my full current code:

public class SchermdeelWerkplaats extends BorderPane{

    //ATD moeder klasse met alle collecties etc.
    private ATD $;

    TableView tabel = new TableView();
    Button nieuwTaak = new Button("Nieuwe taak inboeken");
    final ObservableList<Task> data = FXCollections.observableArrayList();

    public SchermdeelWerkplaats(ATD a) {

        $ = a;

        data.addAll($.agenda);

        tabel.setEditable(false);
        tabel.setPlaceholder(new Label("Geen taken"));

        TableColumn c1 = new TableColumn("datum");
        c1.setMinWidth(200);
        TableColumn c2 = new TableColumn("type");
        c2.setMinWidth(100);
        TableColumn c3 = new TableColumn("uren");
        c3.setMinWidth(100);
        TableColumn c4 = new TableColumn("klaar");
        c4.setMinWidth(200);
        TableColumn c5 = new TableColumn("Werknemer");
        c5.setMinWidth(100);
        TableColumn c6= new TableColumn("Auto");
        c6.setMinWidth(400);
        TableColumn c7= new TableColumn("Actie");
        c7.setMinWidth(400);

        TableColumn col_action = new TableColumn<>("Action");

        col_action.setCellValueFactory(
                new Callback<TableColumn.CellDataFeatures<Task, Boolean>, 
                ObservableValue<Boolean>>() {

            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Task, Boolean> p) {
                return new SimpleBooleanProperty(p.getValue() != null);
            }
        });

        col_action.setCellFactory(
            new Callback<TableColumn<Task, Task>, TableCell<Task, Task>>() {

                @Override
                public TableCell<Task, Task> call(TableColumn<Task, Task> p) {
                    return new ButtonCell();
                }
            }
        );

        c1.setCellValueFactory(
            new PropertyValueFactory<Task,Date>("date")
        );
        c2.setCellValueFactory(
            new PropertyValueFactory<Task,Task.TaskType>("type")
        );
        c3.setCellValueFactory(
            new PropertyValueFactory<Task,Double>("hours")
        );
        c4.setCellValueFactory(
            new PropertyValueFactory<Task,Boolean>("done")
        );
        c5.setCellValueFactory(
            new PropertyValueFactory<Task,Employee>("employee")
        );
        c6.setCellValueFactory(
            new PropertyValueFactory<Task,Car>("car")
        );

        tabel.getColumns().addAll(c1, c2, c3, c4, c5, c6, c7);
        tabel.setItems(data);

        setCenter(tabel);
        setBottom(nieuwTaak);

    }

    //letterlijk van internet geplukt en datatype aangepast
    private class ButtonCell extends TableCell<Task, Task> {


        private Button cellButton;

        ButtonCell(){
              cellButton = new Button("jjhjhjh");
            cellButton.setOnAction(new EventHandler<ActionEvent>(){

                @Override
                public void handle(ActionEvent t) {
                    // do something when button clicked
                    Task record = getItem();
                    // do something with record....
                }
            });
        }

        //Display button if the row is not empty
        @Override
        protected void updateItem(Task record, boolean empty) {
            super.updateItem(record, empty);
            if(!empty){
                cellButton.setText("Something with "+record);
                setGraphic(cellButton);
            } else {
                setGraphic(null);
            }
        }
    }

}

现在我必须创建一个 ButtonCell extends TableCell 的部分是可以理解的.但是如何将其分配给列?

Now the part where I have to create a ButtonCell extends TableCell is understandable. But how to assign this to the column?

我明白这一点:

c1.setCellValueFactory(
        new PropertyValueFactory<Task,Date>("date")
    );

但不是这个:

           TableColumn col_action = new TableColumn<>("Action");

            col_action.setCellValueFactory(
                    new Callback<TableColumn.CellDataFeatures<Task, Boolean>, 
                    ObservableValue<Boolean>>() {

                @Override
                public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Task, Boolean> p) {
                    return new SimpleBooleanProperty(p.getValue() != null);
                }
            });

            col_action.setCellFactory(
                new Callback<TableColumn<Task, Task>, TableCell<Task, Task>>() {

                    @Override
                    public TableCell<Task, Task> call(TableColumn<Task, Task> p) {
                        return new ButtonCell();
                    }
                }
            );

推荐答案

为了能够渲染列,TableColumn 需要 cellValueFactory.但是底层数据模型中不存在action"列.在这种情况下,我只是给 cellValueFactory 一些虚拟值并继续:

To be able to render the column, TableColumn needs cellValueFactory. But the "action" column does not exist in underlying data model. In this case, I just give some dummy value to cellValueFactory and move on:

public class JustDoIt extends Application {

    private final TableView<Person> table = new TableView<>();
    private 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")
            );

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

    @Override
    public void start(Stage stage) {
        stage.setWidth(450);
        stage.setHeight(500);

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

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));

        TableColumn actionCol = new TableColumn("Action");
        actionCol.setCellValueFactory(new PropertyValueFactory<>("DUMMY"));

        Callback<TableColumn<Person, String>, TableCell<Person, String>> cellFactory
                = //
                new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
            @Override
            public TableCell call(final TableColumn<Person, String> param) {
                final TableCell<Person, String> cell = new TableCell<Person, String>() {

                    final Button btn = new Button("Just Do It");

                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                            setText(null);
                        } else {
                            btn.setOnAction(event -> {
                                Person person = getTableView().getItems().get(getIndex());
                                System.out.println(person.getFirstName()
                                        + "   " + person.getLastName());
                            });
                            setGraphic(btn);
                            setText(null);
                        }
                    }
                };
                return cell;
            }
        };

        actionCol.setCellFactory(cellFactory);

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

        Scene scene = new Scene(new Group());

        ((Group) scene.getRoot()).getChildren().addAll(table);

        stage.setScene(scene);
        stage.show();
    }

    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);
        }

    }
}

这篇关于如何在 JavaFX 表视图中添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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