这次StringConverter正在采取不同的行动

时间:2014-07-04 21:46:45

标签: javafx

Books.java

`final class Books extends Group {

private TableView table = new TableView();
private ObservableList<Book> data;
//private ObservableList<Person> plist;

final HBox hb = new HBox();
final TextField Title = new TextField();
final TextField Author = new TextField();
final TextField Publisher = new TextField();
final TextField Copywrite = new TextField();
final TextField ISBN = new TextField();
final Boolean CheckedOut = false;
final Label Whom;
final Button addButton = new Button("Add");
Boolean FirstRead = true;
//StringConverter<Person> converter;

public final class Book {

    private final SimpleStringProperty title;
    private final SimpleStringProperty author;
    private final SimpleStringProperty publisher;
    private final SimpleStringProperty copywrite;
    private final SimpleStringProperty isbn;
    private final BooleanProperty checkedout;
    private final SimpleStringProperty who;

    Book(String Titl, String Auth, String Publ,
            String Cpywrit, String IsBn, Boolean ChkdOut, String WHO) {

        this.title = new SimpleStringProperty(Titl);
        this.author = new SimpleStringProperty(Auth);
        this.publisher = new SimpleStringProperty(Publ);
        this.copywrite = new SimpleStringProperty(Cpywrit);
        this.isbn = new SimpleStringProperty(IsBn);
        this.checkedout = new SimpleBooleanProperty(ChkdOut);
        this.who = new SimpleStringProperty(WHO);
    }

    public boolean isCheckedOut() {
        return checkedout.get();
    }

    public void setCheckedOut(boolean international) {
        this.checkedout.set(international);
    }

    public BooleanProperty isCheckedOutProperty() {
        return checkedout;
    }

    public String getTitle() {
        return title.get();
    }

    public void setTitle(String Title) {
        title.set(Title);
    }

    public String getAuthor() {
        return author.get();
    }

    public void setAutor(String Author) {
        author.set(Author);
    }

    public String getPublisher() {
        return publisher.get();
    }

    public void setPublisher(String Publisher) {
        publisher.set(Publisher);
    }

    public String getCopywrite() {
        return copywrite.get();
    }

    public void setCopywrite(String Copywrite) {
        copywrite.set(Copywrite);
    }

    public String getIsbn() {
        return isbn.get();
    }

    public void setIsbn(String ISBN) {
        isbn.set(ISBN);
    }

    public Boolean getIo() {
        return checkedout.get();
    }

    public void setIo(Boolean CheckedOut) {
        checkedout.set(CheckedOut);
    }

    public String getWho() {
        return who.get();
    }

    public void setWho(String Who) {
        who.set(Who);
    }

    public String isWhoProperty() {
        return getWho();
    }
}

public Books(final File User) throws IOException {

    this.Whom = new Label("inLibrary");
    this.data = FXCollections.<Book>observableArrayList(
            (Book bk) -> new Observable[]{bk.isCheckedOutProperty()
            });

    PhoneList list = new PhoneList(User);


    final Label label = new Label("Book List");
    label.setFont(new Font("Arial", 20));
    table.setPrefSize(600, 400);
    table.setEditable(true);
    TableColumn nameCol = bookName();
    TableColumn authorCol = bookAuthor();
    TableColumn publisherCol = bookPublisher();
    TableColumn copywriteCol = bookCopywrite();
    TableColumn isbnCol = bookISBN();
    TableColumn<Book, Boolean> ioCol = ioCol();

///// START work area
    final TableColumn whoCol;
    whoCol = new TableColumn<>("Who to");
    whoCol.setMinWidth(100);
    whoCol.setEditable(true);
    whoCol.setCellValueFactory(
            new PropertyValueFactory<Person, String>("who"));
    whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist));

////////////////////////////////////////////////////////////////////////////////
    //whoCol.setCellValueFactory(new PropertyValueFactory<>("who"));
    //whoCol.setCellFactory(ComboBoxTableCell.<String, Person>forTableColumn(converter, plist));
    //whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist));

    /*       
     whoCol.setOnEditCommit((TableColumn.CellEditEvent<Book, String> t) -> {
     ((Book) t.getTableView().getItems().get(
     t.getTablePosition().getRow()))
     .setWho(t.getNewValue());
     try {
     writeFile(User);
     } catch (IOException ex) {
     Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
     }
     });
     */
//// END work area
    AddBook(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol, User);

    data.addListener((javafx.collections.ListChangeListener.Change<? extends Book> change) -> {
        while (change.next()) {
            if (change.wasUpdated() && FirstRead != true) {
                try {
                    System.out.println("List changed");
                    writeFile(User);
                } catch (IOException ex) {
                    Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });
    final VBox vbox = new VBox();
    vbox.setSpacing(5);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(label, table, hb);
    getChildren().addAll(vbox);
    try {
        readFile(User);
    } catch (Exception ex) {
        Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private TableColumn<Book, Boolean> ioCol() {
    final TableColumn<Book, Boolean> ioCol = new TableColumn<>("In/Out");
    ioCol.setMinWidth(50);
    ioCol.setEditable(true);
    ioCol.setCellValueFactory(new PropertyValueFactory<>("isCheckedOut"));
    final Callback<TableColumn<Book, Boolean>, TableCell<Book, Boolean>> iocellFactory = CheckBoxTableCell.forTableColumn(ioCol);
    ioCol.setCellFactory((TableColumn<Book, Boolean> column) -> {
        TableCell<Book, Boolean> iocell = iocellFactory.call(column);
        iocell.setAlignment(Pos.CENTER);
        return iocell;
    });
    ioCol.setCellFactory(iocellFactory);
    return ioCol;
}

private TableColumn bookISBN() {
//Column ISBN Number
    TableColumn isbnCol = new TableColumn("ISBN #");
    isbnCol.setMinWidth(100);
    isbnCol.setCellValueFactory(
            new PropertyValueFactory<>("isbn"));
    isbnCol.setCellFactory(TextFieldTableCell.forTableColumn());
    return isbnCol;
}

private TableColumn bookCopywrite() {
//Column Copywrite
    TableColumn copywriteCol = new TableColumn("Copywrite");
    copywriteCol.setMinWidth(100);
    copywriteCol.setCellValueFactory(
            new PropertyValueFactory<>("copywrite"));
    copywriteCol.setCellFactory(TextFieldTableCell.forTableColumn());
    return copywriteCol;
}

private TableColumn bookPublisher() {
//Column Publisher
    TableColumn publisherCol = new TableColumn("Publisher");
    publisherCol.setMinWidth(100);
    publisherCol.setCellValueFactory(
            new PropertyValueFactory<>("publisher"));
    publisherCol.setCellFactory(TextFieldTableCell.forTableColumn());
    return publisherCol;
}

private TableColumn bookAuthor() {
//Column Author
    TableColumn authorCol = new TableColumn("Author");
    authorCol.setMinWidth(100);
    authorCol.setCellValueFactory(
            new PropertyValueFactory<>("author"));
    authorCol.setCellFactory(TextFieldTableCell.forTableColumn());
    return authorCol;
}

private TableColumn bookName() {
// Column Name
    TableColumn nameCol = new TableColumn("Title");
    nameCol.setMaxWidth(100);
    nameCol.setCellValueFactory(
            new PropertyValueFactory<>("title"));
    nameCol.setCellFactory(TextFieldTableCell.forTableColumn());
    return nameCol;
}

private void AddBook(TableColumn nameCol, TableColumn authorCol, TableColumn publisherCol,
        TableColumn copywriteCol, TableColumn isbnCol, TableColumn ioCol, TableColumn whoCol, final File User) {
    table.setItems(data);
    table.getColumns().addAll(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol);

    addButton.setOnAction(
            new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent e) {
                    addBook();
                    try {
                        writeFile(User);
                    } catch (IOException ex) {
                        Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                private void addBook() {
                    data.add(new Book(
                                    Title.getText(),
                                    Author.getText(),
                                    Publisher.getText(),
                                    Copywrite.getText(),
                                    ISBN.getText(),
                                    CheckedOut,
                                    Whom.getText()
                            ));

                    Title.clear();
                    Author.clear();
                    Publisher.clear();
                    Copywrite.clear();
                    ISBN.clear();
                }
            });

    hb.getChildren().addAll(Title, Author, Publisher,
            Copywrite, ISBN, addButton);
    hb.setSpacing(10);
    Title.setPromptText("Tile of Book");
    Title.setMaxWidth(nameCol.getPrefWidth());

    Author.setMaxWidth(authorCol.getPrefWidth());
    Author.setPromptText("Author");

    Publisher.setMaxWidth(publisherCol.getPrefWidth());
    Publisher.setPromptText("Publisher");

    Copywrite.setMaxWidth(copywriteCol.getPrefWidth());
    Copywrite.setPromptText("Year Copywrite");

    ISBN.setMaxWidth(isbnCol.getPrefWidth());
    ISBN.setPromptText("ISBN #");
}

private void writeFile(File User) throws IOException {
    File file = new File(User + "/Books.txt");
    FileWriter fw = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter outFile = new PrintWriter(bw);

    if (table.getItems() != null) {
        data.stream().map((data1) -> {
            if (data1.getTitle().equals("")) {
                data1.setTitle("No_Title");
            }
            return data1;
        }).map((data1) -> {
            if (data1.getAuthor().equals("")) {
                data1.setAutor("No_Author");
            }
            return data1;
        }).map((data1) -> {
            if (data1.getPublisher().equals("")) {
                data1.setPublisher("No_Publisher");
            }
            return data1;
        }).map((data1) -> {
            if (data1.getCopywrite().equals("")) {
                data1.setCopywrite("No_Copywrite");
            }
            return data1;
        }).map((data1) -> {
            if (data1.getIsbn().equals("")) {
                data1.setIsbn("No_ISBN");
            }
            return data1;
        }).map((data1) -> {
            if (data1.getWho().equals("")) {
                data1.setWho("InLibrary");
            }
            return data1;
        }).map((data1) -> {
            outFile.println(data1.getTitle());
            return data1;
        }).map((data1) -> {
            outFile.println(data1.getAuthor());
            return data1;
        }).map((data1) -> {
            outFile.println(data1.getPublisher());
            return data1;
        }).map((data1) -> {
            outFile.println(data1.getCopywrite());
            return data1;
        }).map((data1) -> {
            outFile.println(data1.getIsbn());
            return data1;
        }).map((data1) -> {
            outFile.println(data1.getIo());
            return data1;
        }).forEach((data1) -> {
            outFile.println(data1.getWho());
        });
        outFile.close();
    }
}

private void readFile(File User) throws Exception {
    try {
        String name, author, publisher, copywrite, isbn, whom;
        Boolean InOut;
        try (Scanner inFile = new Scanner(new File(User + "/Books.txt"))) {
            while (inFile.hasNextLine()) {
                name = inFile.next();
                author = inFile.next();
                publisher = inFile.next();
                copywrite = inFile.next();
                isbn = inFile.next();
                InOut = inFile.nextBoolean();
                whom = inFile.next();

                data.add(new Book(name, author, publisher, copywrite,
                        isbn, InOut, whom));
            }
        }
        table.setItems(data);

    } //insert catch statements
    catch (FileNotFoundException exception) {
        System.out.println("File not found");
    } catch (ArrayIndexOutOfBoundsException AIOOBexception) {
        System.out.println("Array Index is out of bounds");
    } catch (IllegalArgumentException IAexception) {
        System.out.println("Divide by zero error");
    } catch (NoSuchElementException NAexception) {
    }
    FirstRead = false;
}
}`  

PhoneList.java

`final class PhoneList extends Group {

private TableView table = new TableView();
final ObservableList<Person> phonelist = FXCollections.observableArrayList();
final HBox hb = new HBox();

public PhoneList(final File User) {
    final Label label = new Label("Phone List");
    label.setFont(new Font("Arial", 20));

    table.setEditable(true);

    TableColumn firstNameCol = new TableColumn("First Name");
    firstNameCol.setMaxWidth(100);
    firstNameCol.setCellValueFactory(
            new PropertyValueFactory<>("firstName"));
    firstNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
    firstNameCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Person, String>>() {
                @Override
                public void handle(CellEditEvent<Person, String> t) {
                    try {
                        ((Person) t.getTableView().getItems().get(
                                t.getTablePosition().getRow())).setFirstName(t.getNewValue());
                        writeFile(User);
                    } catch (IOException ex) {
                        Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

    TableColumn lastNameCol = new TableColumn("Last Name");
    lastNameCol.setMinWidth(100);
    lastNameCol.setCellValueFactory(
            new PropertyValueFactory<>("lastName"));
    lastNameCol.setCellFactory(TextFieldTableCell.forTableColumn());
    lastNameCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Person, String>>() {
                @Override
                public void handle(CellEditEvent<Person, String> t) {
                    try {
                        ((Person) t.getTableView().getItems().get(
                                t.getTablePosition().getRow())).setLastName(t.getNewValue());
                        writeFile(User);
                    } catch (IOException ex) {
                        Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

    TableColumn phoneNumCol = new TableColumn("Phone Number");
    phoneNumCol.setMinWidth(100);
    phoneNumCol.setCellValueFactory(
            new PropertyValueFactory<>("phoneNum"));
    phoneNumCol.setCellFactory(TextFieldTableCell.forTableColumn());
    phoneNumCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Person, String>>() {
                @Override
                public void handle(CellEditEvent<Person, String> t) {
                    try {
                        ((Person) t.getTableView().getItems().get(
                                t.getTablePosition().getRow())).setPhoneNum(t.getNewValue());
                        writeFile(User);
                    } catch (IOException ex) {
                        Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

    TableColumn emailCol = new TableColumn("Email");
    emailCol.setMinWidth(120);
    emailCol.setCellValueFactory(
            new PropertyValueFactory<>("email"));
    emailCol.setCellFactory(TextFieldTableCell.forTableColumn());
    emailCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Person, String>>() {
                @Override
                public void handle(CellEditEvent<Person, String> t) {
                    try {
                        ((Person) t.getTableView().getItems().get(
                                t.getTablePosition().getRow())).setEmail(t.getNewValue());
                        writeFile(User);
                    } catch (IOException ex) {
                        Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

    table.setItems(phonelist);

    table.getColumns().addAll(firstNameCol, lastNameCol, phoneNumCol, 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 addPhoneNum = new TextField();
    addPhoneNum.setMaxWidth(lastNameCol.getPrefWidth());
    addPhoneNum.setPromptText("Phone Number");
    final TextField addEmail = new TextField();
    //addEmail.setMaxWidth(emailCol.getPrefWidth());
    addEmail.setPrefWidth(175);
    addEmail.setPromptText("Email");

    final Button addButton = new Button("Add");
    addButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            try {
                phonelist.add(new Person(
                        addFirstName.getText(),
                        addLastName.getText(),
                        addPhoneNum.getText(),
                        addEmail.getText()));
                addFirstName.clear();
                addLastName.clear();
                addPhoneNum.clear();
                addEmail.clear();
                writeFile(User);
            } catch (IOException ex) {
                Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    hb.getChildren().addAll(addFirstName, addLastName, addPhoneNum, 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);

    getChildren().addAll(vbox);
    try {
        readFile(User);
    } catch (Exception ex) {
        Logger.getLogger(PhoneList.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void readFile(File User) throws Exception {
    try {
        String fN, lN, pNum, eMail;
        try (Scanner inFile = new Scanner(new File(User + "/PhoneList.txt"))) {
            while (inFile.hasNextLine()) {
                fN = inFile.next();
                lN = inFile.next();
                pNum = inFile.next();
                eMail = inFile.next();

                phonelist.add(new Person(fN, lN, pNum, eMail));
            }
        }
        table.setItems(phonelist);
    } //insert catch statements
    catch (FileNotFoundException exception) {
        System.out.println("File not found");
    } catch (ArrayIndexOutOfBoundsException AIOOBexception) {
        System.out.println("Array Index is out of bounds");
    } catch (IllegalArgumentException IAexception) {
        System.out.println("Divide by zero error");
    } catch (NoSuchElementException NAexception) {
    }
}

public void writeFile(File User) throws IOException {
    File file = new File(User + "/PhoneList.txt");
    FileWriter fw = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter outFile = new PrintWriter(bw);

    if (table.getItems() != null) {
        for (int i = 0; i < phonelist.size(); i++) {
            outFile.println(phonelist.get(i).getFirstName());
            outFile.println(phonelist.get(i).getLastName());
            if (phonelist.get(i).getPhoneNum().equals("")) {
                phonelist.get(i).setPhoneNum("No_Phone");
            }
            if (phonelist.get(i).getEmail().equals("")) {
                phonelist.get(i).setEmail("No_Email");
            }
            outFile.println(phonelist.get(i).getPhoneNum());
            outFile.println(phonelist.get(i).getEmail());
        }
        outFile.close();
    }
}

public static class Person {

    private final SimpleStringProperty firstName;
    private final SimpleStringProperty lastName;
    private final SimpleStringProperty phoneNum;
    private final SimpleStringProperty eMail;

    Person(String fName, String lName, String pNum, String email) {
        this.firstName = new SimpleStringProperty(fName);
        this.lastName = new SimpleStringProperty(lName);
        this.phoneNum = new SimpleStringProperty(pNum);
        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 lName) {
        lastName.set(lName);
    }

    public String getPhoneNum() {
        return phoneNum.get();
    }

    public void setPhoneNum(String pNum) {
        phoneNum.set(pNum);
    }

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

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

    public String getName() {
        String Name = getFirstName() + "_" + getLastName();
        return Name;
    }

    public Observable isWhoProperty() {
        return firstName;
    }

    @Override
    public String toString() {
        String Name = getFirstName() + "_" + getLastName();
        return Name;
    }

}

class EditingCell extends TableCell<Person, String> {

    private TextField textField;

    public EditingCell() {
    }

    @Override
    public void startEdit() {
        if (!isEmpty()) {
            super.startEdit();
            createTextField();
            setText(null);
            setGraphic(textField);
            textField.selectAll();
        }
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();

        setText((String) getItem());
        setGraphic(null);
    }

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            if (isEditing()) {
                if (textField != null) {
                    textField.setText(getString());
                }
                setText(null);
                setGraphic(textField);
            } else {
                setText(getString());
                setGraphic(null);
            }
        }
    }

    private void createTextField() {
        textField = new TextField(getString());
        textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
        textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> arg0,
                    Boolean arg1, Boolean arg2) {
                if (!arg2) {
                    commitEdit(textField.getText());
                }
            }
        });
    }

    private String getString() {
        return getItem() == null ? "" : getItem();
    }
}
}`  

有了这两个,我确实让ComboBoxTableCell正常工作......非常感谢你。现在是时候弄清楚如何将它保存到.txt文件。嗯想不出更多的话要说 - 确保你也得到MykeZ文件夹及其内容。但是这个版本只需要它可以工作,所以你可以在必要时添加新的数据。

`final TableColumn<Book, Person> whoCol;
    whoCol = new TableColumn<>("Who to");
    whoCol.setMinWidth(100);
    whoCol.setEditable(true);
    whoCol.setCellValueFactory(new PropertyValueFactory("who"));
    whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(list.phonelist));
    whoCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Book, Person>>() {

        public void handle(TableColumn.CellEditEvent<Book, Person> evt) {
            try {
                evt.getRowValue().setWho(evt.getNewValue().getName());
                writeFile(User);
            } catch (IOException ex) {
                Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });`  

并且已经完成请在这篇帖子中给出你的自信,我非常高兴谢谢你最好的

1 个答案:

答案 0 :(得分:0)

我真的不明白这个问题,但你应该这样做。

编辑:从简要地看你的代码,你可能会尝试做这样的事情;

import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class ComboBoxTable extends Application {

    @Override
    public void start(Stage stage) {
        ObservableList<Person> persons = FXCollections.observableArrayList();
        persons.addAll(new Person("Jack"),new Person("Jill"),new Person("John"));

        ObservableList<Book> books = FXCollections.observableArrayList();
        for (int i=1;i<5;i++)books.add(new Book(i*100,new Person("wrong guy")));

        StringConverter<Person> cvrt = new StringConverter<Person>(){
            @Override
            public String toString(Person person) {
                return person.getName();
            }
            @Override
            public Person fromString(String string) {
                return null;
            }
        };

        TableView<Book> tv = new TableView(books);
        tv.setEditable(true);
        tv.getSelectionModel().setCellSelectionEnabled(true);

        TableColumn<Book, Integer> numCol = new TableColumn("Book Num");
        numCol.setCellValueFactory(new PropertyValueFactory("num"));

        TableColumn<Book, Person> nameCol = new TableColumn("Name");
        nameCol.setCellValueFactory(new PropertyValueFactory("person"));
        nameCol.setCellFactory(ComboBoxTableCell.<Book, Person>forTableColumn(cvrt,persons));

        tv.getColumns().addAll(numCol, nameCol);
        StackPane root = new StackPane(tv);
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.show();
    }

    public class Person{
        SimpleStringProperty name;

        public Person(String name) {
            this.name = new SimpleStringProperty(name);
        }

        public SimpleStringProperty nameProperty() {
            return name;
        }

        public String getName() {
            return name.get();
        }
        //in simple cases you can just do this and not use a string converter
        @Override 
        public String toString(){
            return name.get();
        }
    }

    public class Book{
        SimpleIntegerProperty num;
        SimpleObjectProperty<Person> person;

        public Book(int num, Person person) {
            this.num = new SimpleIntegerProperty(num);
            this.person = new SimpleObjectProperty<>(person);
        }

        public SimpleIntegerProperty numProperty() {
            return num;
        }

        public SimpleObjectProperty<Person> personProperty() {
            return person;
        }
    }
}

查看TableView,TableColumn和ComboBoxTableCell documentation并注意<S,T>

您获取对Person的引用的原因是因为ComboBox不知道如何将其转换为字符串。我放了一些简单的代码来覆盖Person类的toString()方法。如果你没有指定StringConverter,它就不会知道如何转换,只是对对象使用toString()。

再次编辑:查看您的Book类,您有StringProperty谁和您尝试在该字段中存储人。查看我的代码,我使用ObjectProperty <Person>

您可以按照自己的方式执行操作,但在我的示例中覆盖Person类中的toString(),并且不要使用StringConverter。

        @Override 
        public String toString(){
            return name.get();
       }

然后像这样制作TableColumn并使用类型<Book, Person>

    TableColumn<Book, Person> whoCol = new TableColumn<>("Who to");
    whoCol.setMinWidth(100);
    //editable is true for columns by default. 
    whoCol.setCellValueFactory(new PropertyValueFactory("who"));
    whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(p.phonelist));
    whoCol.setOnEditCommit((evt) -> {
        evt.getRowValue().setWho(evt.getNewValue().getName());
    });

我创建了一个onEditCommit,因此Book类将知道如何存储Person信息。