如何在Scala中创建可更新的tableview单元格

时间:2015-11-16 10:40:58

标签: scala scalafx

我创建了一个包含其组件的tableview,分配了cellValueFactory并将属性editable设置为true。在我的代码中,我有以下内容:

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

有了它,我设法创建将其转换为textfield并允许输入它。但是,在完成输入后,文本在编辑之前反转回前一个文本。我应该包含哪些类型/代码,以确保文本正确更新? 我试过在谷歌搜索,但到目前为止还没有解释。

1 个答案:

答案 0 :(得分:0)

如上所述,您应该能够编辑表格editable = true并添加带有文本字段的单元格工厂,例如:

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

JavaFX Table View Tutorial还建议使用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)
            }
          }
        )
      }
    }
  }
}