简体   繁体   English

如何使表格单元格编辑中的更改永久生效?

[英]How do I make the changes from table cell editing permanent?

I'm trying to save the changes to the table when I run the application again. 当我再次运行应用程序时,我试图将更改保存到表中。 The code below allows the user to edit the cells and it commits the changes, but when I run the application again, the changes are not saved. 下面的代码允许用户编辑单元格并提交更改,但是当我再次运行应用程序时,更改不会保存。 How do I make the changes from table cell editing permanent? 如何使表格单元格编辑中的更改永久生效? The code is below. 代码如下。 (which is from oracle's website). (来自oracle的网站)。 I tried playing around with it but with no success. 我尝试使用它,但是没有成功。

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class TableViewSample extends Application {

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

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

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(450);
        stage.setHeight(550);

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

        table.setEditable(true);

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

        firstNameCol.setCellFactory(TextFieldTableCell.<Person>forTableColumn());
        firstNameCol.setOnEditCommit(
            (CellEditEvent<Person, String> t) -> {
                ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setFirstName(t.getNewValue());
        });


        TableColumn<Person, String> lastNameCol = 
            new TableColumn<>("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(
            new PropertyValueFactory<>("lastName"));
       lastNameCol.setCellFactory(TextFieldTableCell.<Person>forTableColumn());
       lastNameCol.setOnEditCommit(
            (CellEditEvent<Person, String> t) -> {
                ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setLastName(t.getNewValue());
        });

        TableColumn<Person, String> emailCol = new TableColumn<>("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
            new PropertyValueFactory<>("email"));
        emailCol.setCellFactory(TextFieldTableCell.<Person>forTableColumn());       
        emailCol.setOnEditCommit(
            (CellEditEvent<Person, String> t) -> {
                ((Person) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setEmail(t.getNewValue());
        });

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

        final TextField addFirstName = new TextField();
        addFirstName.setPromptText("First Name");
        addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
        final TextField addLastName = new TextField();
        addLastName.setMaxWidth(lastNameCol.getPrefWidth());
        addLastName.setPromptText("Last Name");
        final TextField addEmail = new TextField();
        addEmail.setMaxWidth(emailCol.getPrefWidth());
        addEmail.setPromptText("Email");

        final Button addButton = new Button("Add");
        addButton.setOnAction((ActionEvent e) -> {
            data.add(new Person(
                    addFirstName.getText(),
                    addLastName.getText(),
                    addEmail.getText()));
            addFirstName.clear();
            addLastName.clear();
            addEmail.clear();
        });

        hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
        hb.setSpacing(3);

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

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

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

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty 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 String getLastName() {
            return lastName.get();
        }

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

        public String getEmail() {
            return email.get();
        }

        public void setEmail(String fName) {
            email.set(fName);
        }
    }
}

您将不得不使用一个持久层,例如一个数据库来存储值并在以后检索它们,或者简单地使用一个文本文件,在其中写入被枚举的值,每个值由您选择的分隔符分隔。

From the comments I understand that the question is how to get the data from the table, so you can write it to a database. 从注释中,我了解到问题是如何从表中获取数据,因此您可以将其写入数据库。
The table information is represented by ObservableList<Person> data . 表信息由ObservableList<Person> data It always reflects the actual table information. 它始终反映实际的表信息。
To get the information simply loop over it. 要获取信息,只需在其上循环即可。 Run the following test : 运行以下测试:

Add a method to print some of the table's data: 添加一种方法来打印表的一些数据:

private void printSomeTableData() {

    for(Person p : data) {

        System.out.println(p.getFirstName() + ", " + p.lastName.get()+ ", " +p.getEmail());
    }
} 

In the constructor add a button to use this method: 在构造函数中添加一个按钮以使用此方法:

final Button printButton = new Button("Print");
printButton.setOnAction(e -> printSomeTableData());
//change 
// hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
//to
hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton, printButton);

Whenever you press "print" updated table data prints out. 只要您按“打印”,就会打印出更新的表格数据。
I hope this simple test makes the mechanism clear. 我希望这个简单的测试可以使机制更清晰。 Think of TableView as a graphic representation of ObservableList<Person> data . TableView视为ObservableList<Person> data的图形表示。 Any change in the table information is reflected in data . 表信息的任何更改都会反映在data

From comments I've seen that you didn't know how to get the values from textfields... Well, this is very simple, try something like this: textFieldName.getText() and you will have the value of that TextField :) 从评论中我已经看到您不知道如何从文本字段中获取值...嗯,这很简单,请尝试如下操作:textFieldName.getText(),您将获得该TextField的值:)

EDIT: For iterating over a TableView do something like this: 编辑:对于遍历TableView做这样的事情:

   for (Person person : table.getItems()){ writeToDatabase(person.getFirstName());} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在禁用编辑的JTable单元格中选择文本? - How do I make it possible to select text in a JTable cell with editing disabled? 当失去焦点或左键单击发生在JTree位置之外时,如何使JTree停止单元格编辑? - How do I make JTree stop cell editing, when either Focus Lost or Left Click occurs outside JTree Location? 如何允许用户永久更改日志级别? - How to allow user to make permanent changes to log levels? 如何调用永久命令提示符? - How do I call a permanent command prompt? 我如何发现永久世代中的东西 - How do I discover what is in the permanent generation JavaFX 表格单元格编辑 - JavaFX Table Cell Editing PreparedStatement是仅对数据库进行临时更改还是可以使其永久更改? - Does PreparedStatement only make temporary changes in database or can I make it permanent? 如何从另一个类制作数据库表条目? - How do I make database table entries from another class? 当我在查看器中进行更改时,如何防止它执行所有这些操作? - How do I prevent it from doing all of them when I make changes in the viewholder? 如何从 jsp/servlet 中表数据单元格内的文本框中获取值? - How do I get a value from a textbox that is inside of a table data cell in jsp/servlet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM