2

我创建了一个表格视图,其中包含它们的组件,分配了 cellValueFactory 并将属性设置editabletrue. 在我的代码中,我有以下内容:

    ...
    tableID.selectionModel().selectedItem.onChange(
          (_, _, newValue) => col_uname.setCellFactory(TextFieldTableCell.forTableColumn());
    ...

有了它,我设法将其转换为文本字段并允许输入。但是,在完成输入后,文本又回到了编辑前的前一个文本。我应该包含什么类型/代码以确保文本正确更新?我试过在谷歌上搜索,但到目前为止还没有任何解释。

4

1 回答 1

1

正如您所提到的,您应该能够通过editable = true添加带有文本字段的单元格工厂来编辑表格,例如:

new TableColumn[Person, String] {
  text = "First Name"
  cellValueFactory = {_.value.firstName}
  cellFactory = TextFieldTableCell.forTableColumn()
  prefWidth = 180
}

JavaFX 表视图教程还建议使用OnEditCommit. 不确定这是否真的有必要。这是一个不使用的完整示例OnEditCommit

import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.beans.property.StringProperty
import scalafx.collections.ObservableBuffer
import scalafx.event.ActionEvent
import scalafx.scene.Scene
import scalafx.scene.control.TableColumn._
import scalafx.scene.control.cell.TextFieldTableCell
import scalafx.scene.control.{Button, TableColumn, TableView}
import scalafx.scene.layout.VBox

object EditableTableView extends JFXApp {

  class Person(firstName_ : String, lastName_ : String) {

    val firstName = new StringProperty(this, "firstName", firstName_)
    val lastName  = new StringProperty(this, "lastName", lastName_)

    firstName.onChange { (_, oldValue, newValue) => println(s"Value changed from `$oldValue` to `$newValue`") }
    lastName.onChange { (_, oldValue, newValue) => println(s"Value changed from `$oldValue` to `$newValue`") }
    override def toString = firstName() + " " + lastName()
  }

  val characters = ObservableBuffer[Person](
    new Person("Peggy", "Sue"),
    new Person("Rocky", "Raccoon")
  )

  stage = new PrimaryStage {
    title = "Editable Table View"
    scene = new Scene {
      root = new VBox {
        children = Seq(
          new TableView[Person](characters) {
            editable = true
            columns ++= List(
              new TableColumn[Person, String] {
                text = "First Name"
                cellValueFactory = {_.value.firstName}
                cellFactory = TextFieldTableCell.forTableColumn()
                prefWidth = 180
              },
              new TableColumn[Person, String]() {
                text = "Last Name"
                cellValueFactory = {_.value.lastName}
                cellFactory = TextFieldTableCell.forTableColumn()
                prefWidth = 180
              }
            )
          },
          new Button {
            text = "Print content"
            onAction = (ae: ActionEvent) => {
              println("Characters:")
              characters.foreach(println)
            }
          }
        )
      }
    }
  }
}
于 2015-11-19T01:41:25.357 回答