如何在TableView TableCell中以不同方式为每个字符着色

时间:2017-01-19 21:51:41

标签: scalafx

我有一个tableview,在一列中我希望能够对字符串的每个字符进行单独着色。显然,textFill仅适用于整个单元格,因为我尝试先按字符拆分字符串。我已经包含了根据我的意愿不完全做的下面的代码,但它是指示性的(它仅根据第一个字符更改单元格文本颜色)。如何调整以获得该单元格中的多色输出? [注意:unicode字符是向上和向下箭头]

    val colTick = new TableColumn[Quote, String] {
      editable = false
      text = "Tick"
      prefWidth = 90
      alignmentInParent = scalafx.geometry.Pos.Center
      cellFactory = { _ =>
        new TableCell[Quote, String] {
          item.onChange { (_, _oldTick, newTick) =>
            if (newTick == null) {
              text = null
              graphic = null
            } else {
              if (newTick(0) == '\u2B06') {
                textFill = Color.Green
              } else {
                if (newTick(0) == '\u2B07') textFill = Color.Red else textFill = Color.Black
              }
              text = newTick
            }
          }
        }
      }
      cellValueFactory = {
        _.value.tick
      }
    }

2 个答案:

答案 0 :(得分:1)

一个选项是为每个字符使用单独的Text,因此您可以单独设置其颜色。然后将这些Text合并到HBoxTextFlow或任何合适的内容中。以下是一个示例,其中字符rgb将为彩色,其他字符为黑色:

cellFactory = { _ =>
  new javafx.scene.control.TableCell[Quote, String] {
    override def updateItem(item: String, empty: Boolean): Unit = {
      super.updateItem(item, empty)
      setText(null)
      if (item == null || empty) {
        setGraphic(null)
      } else {
        val texts = item.map { c =>
          val color: Color = c.toLower match {
            case 'r' => Color.Red
            case 'g' => Color.Green
            case 'b' => Color.Blue
            case _ => Color.Black
          }
          new Text {
            text = c.toString
            fill = color
          }
        }
        setGraphic(new HBox(texts: _*))
      }
    }
  }
}

答案 1 :(得分:0)

从@Jarek给出的评论开始,这段代码现在似乎有用了:

      cellFactory = { _ =>
        new TableCell[Quote, String] {
          item.onChange { (_, _oldTick, newTick) =>
            if (newTick == null) {
              text = null
              graphic = null
            } else {
              val texts = newTick.map { c =>
                val color: Color = c match {
                  case '⬇' => Color.Red
                  case '⬆' => Color.Green
                  case '_' => Color.Crimson
                  case '○' => Color.DarkBlue
                  case _ =>Color.Black
                }
                new Text {
                  setText(c.toString)
                  setFill(color)
                }

              }
              graphic = new javafx.scene.layout.HBox(texts: _*)
            }
          }
        }
      }