在TableView中无法理解ComboBoxTableCell

时间:2014-06-30 22:24:17

标签: javafx-8

我已阅读本网站及其他网站上的所有内容;我已经剪切并粘贴了有关此主题的每一行代码(我愿意下注)。这就是结果:

final class Books extends Group {

private TableView table = new TableView();
private ObservableList<Book> data = FXCollections.observableArrayList();
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;

public static 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 ObservableValue<String> whoProperty() {
        return who;
    }
}

public Books(final File User) throws IOException {

    this.Whom = new Label("inLibrary");
    this.data = FXCollections.<Book>observableArrayList(
            (Book bk) -> new Observable[]{bk.isCheckedOutProperty()
            });
    final PhoneList p = 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();

    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(iocellFactor

    final TableColumn<String, Book> whoCol = new TableColumn<>("Who to");
    whoCol.setMinWidth(100);
    whoCol.setEditable(true);
    whoCol.setCellValueFactory(new PropertyValueFactory<>("who"));

    whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {
        @Override
        public String toString(Book string) {
            return string.getWho();
        }
        @Override
        public Book fromString(String string) {
            return null;
        }
    }, data));


    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 bookISBN() {

    TableColumn isbnCol = new TableColumn("ISBN #");
    isbnCol.setMinWidth(100);
    isbnCol.setCellValueFactory(
            new PropertyValueFactory<>("isbn"));
    isbnCol.setCellFactory(TextFieldTableCell.forTableColumn());
    return isbnCol;
}

private TableColumn bookCopywrite() {

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

private TableColumn bookPublisher() {

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

private TableColumn bookAuthor() {

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

private TableColumn bookName() {

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

这会出现以下错误:

Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: mediatracker.Books$Book cannot be cast to java.lang.String
    at mediatracker.Books$1.toString(Books.java:198)

第198行开始:

 whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {

任何人都可以输入ComboBoxTableCell背后的“理论”,并列出实现此目的所需的部分。我想要做的就是更改从另一个文件中的PhoneList中提取的单元格的值。

3 个答案:

答案 0 :(得分:1)

我只是假设第198行是

return (String) object ;

采用匿名StringConverter toString()方法。当您使用堆栈跟踪发布问题时,请始终指出代码中哪条是异常所指向的行。

首先,使用泛型类型而不是原始类型总是更好。而不是

TableColumn whoCol = ...
你应该

TableColumn<S,T> whoCol = ...

使用表格中的数据类型替换S,使用列中数据的类型替换T。既然你没有给出一个完整的例子,我无法猜测S是什么;从错误消息中看起来,列中数据的类型可能是Book

阅读Javadocs for the method you are calling。他们清楚地说明转换器是什么:

  

converter - 一个StringConverter,用于将给定项(类型为T)转换为   用于向用户显示的字符串。

所以,假设表示您的TableColumn正在显示Book假设 data的类型为ObservableList<Book>你应该有像

这样的东西
ObservableList<Book> data = ... ;
TableColumn<S, Book> whoCol = new TableColumn<>("Who to");
// ...
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {

    @Override
    public String toString(Book book) {
        // assuming your Book class defines a getTitle() method, and that's
        // how you want to display it in your ComboBox:
        return book.getTitle(); // or get a String from book some other way
    }

    @Override
    public Book fromString(String string) {
        // I think this is not actually used, as the combo box is not editable
        // So you could probably safely just return null here.
        // But in general:
        Book book = ... ; // create a book from the string
        return book ;
    }
}, data)); 

同样,您可以将S替换为TableView的类型;而且我必须猜测你TableColumn的类型,因为你没有提供一个完整的例子。但这应该足以让你明白这一点。

答案 1 :(得分:0)

您的问题似乎与ComboBoxTableCell没有任何关系。

你的toString()方法错了;您正在尝试将对象强制转换为字符串。这(可能)是你看到java.lang.ClassCastException的原因。你能确认第198行是哪一行吗?

另外,我注意到你的fromString()方法所做的就是返回它的参数。你在这个代码片段中想要实现的目标究竟是什么?你能给我们一些背景信息吗?

答案 2 :(得分:0)

`final TableColumn<Book, String> whoCol = new TableColumn<>("Who to");
    whoCol.setMinWidth(100);
    whoCol.setEditable(true);
    whoCol.setCellValueFactory(new PropertyValueFactory<>("who"));

    whoCol.setCellFactory(ComboBoxTableCell.<Book, String>forTableColumn(p.data.get(myIndex()).toString()));
    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);
        }
    });`

这是有效的 - @James_D感谢您的帮助 - 您向我发送了正确的方向