【问题标题】:Scala Swing: verifying Integer input forTextfieldScala Swing:验证文本字段的整数输入
【发布时间】:2012-07-26 02:36:49
【问题描述】:

我有一个希望从中获取整数输入的 TextField。在之前的c# Wpf版本中,我订阅了PreviewTextInput如下:

private void PrevInp(object sender, TextCompositionEventArgs e)
{
   int temp;
   if (!(int.TryParse(e.Text, out temp)))
      e.Handled = true;
   else
      if (TextAltered == false)
      {
         inp.Text = "";
         TextAltered = true;
      }
}

希望我可以在 Scala 中做一些更简洁的事情。我看到你可以为 inputVerifier 设置一个函数,但是 inputVerifier 只有在 TextField 失去焦点时才会被调用。

我可以像这样使用 KeyTyped 事件:

val intF = new TextField(defInt.toString, 5)
{
   inputVerifier = myV _
   listenTo(keys, this)
   reactions += { case e: KeyTyped => text = text.filter(_.isDigit)}

   def myV(v: Component ): Boolean = text.forall(_.isDigit) 

}

但是在应用过滤器之后会添加新的按键。

【问题讨论】:

    标签: scala user-input validation textinput scala-swing


    【解决方案1】:

    答案是如下使用event.consume

    val intF = new TextField(defInt.toString, 5)
    {
       inputVerifier = myV _
       listenTo(keys)
       reactions +=
       {
          case e: KeyTyped =>     
          {
             if (!e.char.isDigit)
                e.consume           
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多