Skip to content
Tags

Changing the background color of a label in Flex

by Jason on November 9th, 2009

funny how i’ve always laughed at posts that tell you “how to make a scroll bar pink” because those problems seem silly or insignificant.

But after spending an entire afternoon and draining my brain of any trace of reason, I feel I need to let the world know that you can change the background color of a label. I’ve read on forums that say otherwise, but thats not quite true.

The catch is that you need to inherit from the flex label class so you can make the protected property “textField” publicly available somehow. Me, I created the following class:

package {
 import mx.controls.Label;

  public class BGLabel extends Label {
    public function BGLabel() {
      super()
    }

    public function getTextField():* {
      return textField
    }
  }
}

With this, you use the BGLabel instead of the Label class in your mxml. To change the background, in actionscript you would write something like this:

myLabel.getTextField().background = true
myLabel.getTextField().backgroundColor = 0x4499CC

The reason why we need to inherit from Label is because we need access to its TextField class that the Label class is based on. TextField’s are able to change the background color’s, but labels for some reason are not. As the TextField property is protected, the only way we can get at it is to inherit.

Strangely though, if you set up a MOUSE_DOWN event listener for a label, the event passes in the TextField of the Label to the handler, not the label itself.

Other methods I tried to change the label background include using setStyle(), which doesn’t allow you to change the background color of a label. I also tried the opaqueBackground property , but I couldn’t get the background colors switching off and on the way I wanted. I would suggest you play with opaqueBackground first before you access the TextField property. But if you notice it not redrawing properly or other signs of flakiness, don’t waste an afternoon, use the TextField.

From → Actionscript

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS