首页 > 解决方案 > Java FX:从 Observable List 获取和编辑对象

问题描述

我知道方法 list.getSelectionModel().getSelectedItem(); 及其索引版本,但这是我的问题:

我在我的 GUI 中设置了一个列表,其中包含类 Person 的对象。在我的 GUI 中,还有具有该类属性的文本字段(名称、街道、年龄等)。

到目前为止,我所做的是实现一个方法 clickList(),它将使用列表视图中选定对象的数据填充属性字段。所以用户可以从这里编辑它们并按下另一个按钮,然后应该更新这些属性。

我还进行了设置,以便您可以通过在控制器内的“确定”按钮中执行此操作从文本表单创建一个新对象:

     ObservableList<Person> items = FXCollections.observableArrayList();
     items.add(new Person(tf_vn.getText(), tf_nn.getText(),tf_strasse.getText(), tf_plz.getText(), tf_ort.getText(),genderChoice, sliderAge.getValue());
      list.setItems(items);

然而,我正在苦苦挣扎的是对已经存在的人的编辑。有人可以给我一些指示吗?我知道我可以获得选定的对象索引,但我该如何使用它?基本上我只需要找到一种方法来做类似selectedObject.setAge(),selectedObject.setName()等

我查看了所有的 getSelectionModel() 方法,但没有找到解决方案,我确定有一个简单的方法......

提前致谢 !

标签: listobjectjavafxobservablelist

解决方案


这样您就可以访问 selectedObject 的方法

ListView<Person> l = new ListView<>();
...
l.getSelectionModel().getSelectedItem().setFirstName("new name");
l.refresh();

一个完整的例子可能看起来像;

package so;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
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.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
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 TableView<Person> table = new TableView<Person>();
    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<Person, String>("firstName"));

        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));

        TableColumn<Person, String> emailCol = new TableColumn<>("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));

        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(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {

                if (table.getSelectionModel().getSelectedItem() != null) {
                    table.getSelectionModel().getSelectedItem().setFirstName(addFirstName.getText());
                    table.getSelectionModel().getSelectedItem().setLastName(addLastName.getText());
                    table.getSelectionModel().getSelectedItem().setEmail(addEmail.getText());
                    table.refresh();
                } else {
                    data.add(new Person(addFirstName.getText(), addLastName.getText(), addEmail.getText()));
                    addFirstName.clear();
                    addLastName.clear();
                    addEmail.clear();
                }

            }
        });

        table.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> {

// addFirstName.clear(); // addLastName.clear(); // addEmail.clear();

            if (n != null) {

                addFirstName.setText(n.getFirstName());
                addLastName.setText(n.getLastName());
                addEmail.setText(n.getEmail());

                addButton.setText("Edit");

            }
            else {

                addButton.setText("Add");

            }

        });

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

推荐阅读