0

整数入力を取得したい 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) 

}

ただし、フィルターが適用された後に、押された新しいキーが追加されます。

4

1 に答える 1

3

答えは、次のように event.consume を使用することです

val intF = new TextField(defInt.toString, 5)
{
   inputVerifier = myV _
   listenTo(keys)
   reactions +=
   {
      case e: KeyTyped =>     
      {
         if (!e.char.isDigit)
            e.consume           
      }
   }
}
于 2012-07-27T14:11:06.313 に答える