Posts Tagged ‘Label’

JavaFX TextBox and binding the length of the text entered to a Button (in 1.3)

May 12, 2010

Just a quick post, I have started work on a JavaFX project and I came across the following challenge:

I want a Text Box where I can freely enter text, however I need to:

  1. Enable the button associated with the Text Box once I have entered a value (i.e. the length of the string entered is greater than 0) and disable the Button if the text is greater than a specified amount, say 140 (oh, I wonder what I am working on limiting text to 140 characters???)
  2. Count down the number of characters remaining as I type in text, from 140…

Initially I struggled with this as I found the text I entered into the text box didn’t actually commit until I selected another object in the scene (e.g. another text box). This proved a little frustrating and after a while of trying to bind the text being entered to another variable and then setting the Text Box text value to that value I conceded that this cannot be the way. So I was left with a counter that didn’t get updated and a button which wasn’t enabled until I selected another object in the scene. I could not find a posting showing this challenge, maybe everyone else gets it and I just didn’t.

So I looked into the functions available for TextBox and realised that commit() must push the value held at that moment into the text variable and so allow me to successfully bind to the text value. So I configured the TextBox to commit() everytime a key is typed. See below my code, which I am sure will make things clearer:


var tBox : TextBox = TextBox
{
     columns: 20
     selectOnFocus: true
     translateY: 20;
     translateX: 60;

     onKeyTyped: function(ke: KeyEvent):Void
     {
         tBox.commit();
         println("Key pressed, the value of the
                     tBox.text is {tBox.text}");
     }
}

var testString : Label = Label
{
     layoutInfo: LayoutInfo { width: 50; height: 50;}
     translateX: 80;
     translateY: 150;
     text: bind tBox.text.length().toString();
}

var tweetB : Button = Button
{
     translateY: 170;
     translateX: 120;
     text: "Tweet"
     disable: bind if (tBox.text.length() < 14)
                                     false else true;
     action: function()
     {
         println("I go and update my status with the
                             following {tBox.text}");
     }
}

Stage {
 title: "Application title"
 scene: Scene {
 width: 300
 height: 300
 content:
 [
     Group
     {
         content:
         [
              tBox,
              testString,
              tweetB
         ]
     }
 ]
 }

Well, I hope this isn’t so obvious to everyone (perhaps I am having a bad day?) I just wanted to share this in the hope it helps others? I hope so.

Update:

Looks like I could use rawText????