Truncating text in the Flex Label control using the truncateToFit property
The following example shows how you can use the truncateToFit property in the Label control in Flex to truncate strings if they exceed a specified width. The label control will terminate the string with “…” and allow you to roll over the text and read the entire (non-truncated) text in a tool tip, as seen in the following snippet:
<mx:Label text="The quick brown fox jumped over the lazy dog."
truncateToFit="true"
maxWidth="200" />
Full code after the jump.
The following example displays three Label controls:
The first Label control (“default”), simply sets the text property and allows the Label control to size itself to match the length of the text.
The second Label control (“truncateToFit = false”) sets the truncateToFit property to false and sets the maxWidth property to 200 pixels. Because the specified text will not fit within the 200 pixel control, the extra text is not displayed and is cropped off. You can see a portion of a last character in the Label control and rolling over the text will not display a tool tip.
The third Label control (“truncateToFit = true”) sets the truncateToFit property to true and sets the maxWidth property to 200 pixels. Because the specified text will not fit within the 200 pixel control, the extra text is not displayed, but the text displays “…” at the end of the control. No partial characters are displayed and rolling over the text displays a tool tip showing the entire contents of the text string.
<?xml version="1.0" encoding="utf-8"?> <!-- http://blog.flexexamples.com/2008/01/26/truncating-text-in-the-flex-label-control-using-the-truncatetofit-property/ --> <mx:Application name="Label_truncateToFit_test" xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:String id="str">The quick brown fox jumped over the lazy dog.</mx:String> <mx:Form> <mx:FormItem label="default:"> <mx:Label text="{str}" /> </mx:FormItem> <mx:FormItem label="truncateToFit = false:"> <mx:Label truncateToFit="false" text="{str}" maxWidth="200" /> </mx:FormItem> <mx:FormItem label="truncateToFit = true:"> <mx:Label truncateToFit="true" text="{str}" maxWidth="200" /> </mx:FormItem> </mx:Form> </mx:Application>
View source is enabled in the following example.
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
22 Responses to Truncating text in the Flex Label control using the truncateToFit property
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


A quick comment to add that ‘truncateToFit’ won’t show the ‘…’ ending string on HTML Labels. They only get truncated.
Here what you can find in Label.as :
Hey folks, would anyone know how to extend the Label class, so that the tooltip is always shown when you hover over it? whether or not the label is truncated..
@rob there’s a couple of ways I can think of. Inline:
<mx:Label id="_alabel" text="hello" toolTip="{_alabel.text}" />secondly, you could subclass label and override the setter for the text property and assigning the text being set to the tooltip. i haven’t tried this, so this code is off the top of my head:
public class TippedLabel extends Label { override public function set text(o:String) : void { super.text = o; super.toolTip = o; } }Hope that helps.
Cheers,
Chris
Is there a way of using truncateToFit AND getting the Label to wrap? It seems the only way to get truncateToFit is to set a MaxWidth but the only way I have found to get wrapping to work is to set width=100%
One possible solution would be:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.utils.StringUtil; [Bindable] private var longString:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; private var maxStringLength:int = 50; private function truncatedString(source:String):String { var shortString:String = StringUtil.trim(source); shortString = shortString.substr(0, maxStringLength); if (source.length != 0 && source.length > maxStringLength) { shortString += "..."; } return shortString; } ]]> </mx:Script> <mx:Panel layout="absolute" left="10" right="10" bottom="10" top="10"> <mx:TextArea x="10" y="10" maxWidth="200" maxHeight="50" text="{truncatedString(longString)}" id="lblLongText" height="65" wordWrap="true"/> </mx:Panel> </mx:Application><?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.utils.StringUtil; [Bindable] private var longString:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; private var maxStringLength:int = 50; private function truncatedString(source:String):String { var shortString:String = StringUtil.trim(source); shortString = shortString.substr(0, maxStringLength); if (source.length != 0 && source.length > maxStringLength) { shortString += "..."; } return shortString; } ]]> </mx:Script> <mx:Panel layout="absolute" left="10" right="10" bottom="10" top="10"> <mx:TextArea x="10" y="10" maxWidth="200" maxHeight="50" text="{truncatedString(longString)}" id="lblLongText" height="65" wordWrap="true"/> </mx:Panel> </mx:Application>Is there a way to get truncated text to move left and right periodically so you can read the entire label?
is there any way to customize the truncation indicator?
@prashant:
check this:
http://skovalyov.blogspot.com/2007/02/text-control-with-truncatetofit.html
How to get flex to display the ‘…’ ending on truncated HTMLText labels:
1. Place the HTMLText in an invisible label.
The invisible label will convert entity references (e.g. “õ”) to utf8. The text attribute has the result of the conversion.
2. Set the text attribute of the label you want to show to the text attribute of the invisible label converter.
<mx:Label width="210" text="{lblSubcategoryHTML.text}"/>I’m having trouble with this truncateToFit thing: it seems as if Flex does’nt find the appropriate text (“…”) to use – it is always displaying the text cut off and adds “null” to its end instead. Maybe this is because I’m using a differend resource bundle for all my texts (i18n). Which key do I have to use to give the “…” text back to my Flex application? Does anyone know?
Help is really appreciated.
Hey check this
http://ahmadflex.wordpress.com/2009/05/28/flex-marquee-label/
This component extends label. when text is truncated and you hover over the label it will keep scrolling to show all the text until mouse is out
Ahmad
Hey Anne ,
Did you find answer to your question ?
I m also stuck with same problem
Thanks
Hi,
Anne and Sohil,
I had this problem too, I found a solution for me… maybe it works fo you…
In the resourceManager.localeChain, I put two locales:
resourceManager.localeChain = ['pt_BR', 'en_US'];
Flex try to use the first locale, what is not found in the first, is used from the second
(Sorry for my english)
Inside the UITextField you can find the code:
truncationIndicatorResource = resourceManager.getString(“core”, “truncationIndicator”);
So I suppose this is missing within my application because I have my own resource bundle (named differently)…
I will add one with the name “core” and add at least the missing “…” to it again.
Best wishes
I have seen the problem with appending null at the end. Seen it on Linux with flash player debug version 9. Once we upgraded to flash player debug version 10, that problem went away. It isn’t related to the locale stuff cos I dont even use any of the inbuilt locale flex provides.
Hope this helps.
Shilpa
Perhaps slightly off topic:
As far as I know, there is no way to prevent a button from truncating its text, and Adobe have closed the issue without fixing it:
http://bugs.adobe.com/jira/browse/SDK-12992
Adrian,
I believe Adobe closed the enhancement as unable to reproduce. If you have a test that shows a truncated label where truncation shouldn’t be happening, can you please attach it to that bug?
For example, the following example shows a button label that does not truncate itself:
As far as I know, a Button should not truncate its label unless you give the Button control an explicit width or set a left/right constraint. But if you have an example that shows otherwise, please attach it to the JIRA bug and Adobe can investigate.
Thanks,
Peter
Hi,
I am facing an issue while scaling a Label with truncateToFit property as true. While zooming in/out, sometimes the text which is truncated is displayed without ellipses or 1 or 2 ellipses sometimes. I tried setting fontAntiAliasType=”animation” thinking that it might solve the issue.
But it didnt :-(
Please find the code below:
Could anyone of you help me finding whats going wrong here?
Thanks in Advance,Srilatha
If you have width=”100%” and you need to have correct truncation on resize,
use
mx:Label
truncateToFit=”true”
text=”{str}”
minWidth=”0″
It is not working, When i am binding text in mx:Label in flex 4. With .text property it is working fine.
Any solution?
Sachin Dev tripathi
example for previous comment
%lt;mx:Label text={txtname}%gt;