Flex Examples
Determining the number of lines in a TextArea control in Flex
The following example shows how you can get the number of lines in a Flex TextArea control by using the getTextField() method (in the mx_internal namespace) and the numLines property.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/05/08/determining-the-number-of-lines-in-a-textarea-control-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.utils.StringUtil;
private function textArea_change(evt:Event):void {
callLater(updateStats, [evt]);
}
private function updateStats(evt:Event):void {
var nLines:uint = textArea.mx_internal::getTextField().numLines;
var nChars:uint = textArea.length;
var str:String = "{0} characters; {1} lines";
panel.status = StringUtil.substitute(str,
nChars,
nLines);
}
]]>
</mx:Script>
<mx:String id="str" source="lorem.txt" />
<mx:ApplicationControlBar dock="true">
<mx:Form styleName="plain">
<mx:FormItem label="width (%):">
<mx:HSlider id="slider"
minimum="50"
maximum="100"
value="100"
liveDragging="true"
snapInterval="1"
tickInterval="10" />
</mx:FormItem>
</mx:Form>
</mx:ApplicationControlBar>
<mx:Panel id="panel"
percentWidth="{slider.value}"
height="100%">
<mx:TextArea id="textArea"
htmlText="{str}"
condenseWhite="true"
width="100%"
height="100%"
change="textArea_change(event);"
resize="textArea_change(event);" />
</mx:Panel>
</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.
14 Responses to Determining the number of lines in a TextArea control in Flex
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


Thanks much! This helped me out of a long-running bind. Good ol’ mx_internal!
Cheers,
Chris
Another thank you! :) I may never have figured this out from the Flex help!
Hi-
how would I achieve this in an actionscript class? I have a class extending textArea and I’m trying to access the textField methods by using
import mx.core.mx_internal; (right after the package definition)
this.mx_internal::getTextField().numLines; (in a function)
I get no warnings, but I still get a null object reference error when I debug:(
help!
-Randy
Thanks, was trying to figure out how to reach the numLines by reading the docs and didn’t find anything of value. Thankfully this blogpost fixed that!
(So odd this number isn’t exposed by default.)
Johan,
You can file an enhancement request to make the property public at http://bugs.adobe.com/flex/. That won’t guarantee that it will happen, but it will at least show Adobe there is interest.
It may possibly have been made internal if it was “expensive” to calculate, so they didn’t want to expose it too easily. You could also try extending the TextArea control and making this value public in your custom component.
Peter
Looks like you extended TextArea so, should be able to use just “this.textField.numLines”
Hi,
Can you please give me an example of how to assign “tabStops” format property to textarea control?
Thanks,
Karthik
Karthik,
Try something like the following:
<?xml version="1.0" encoding="utf-8"?> <mx:Application name="TextArea_tabStops_test" xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Script> <![CDATA[ private function init1():void { var tf:TextFormat = new TextFormat(); tf.tabStops = [100, 200, 300, 400]; textArea1.mx_internal::getTextField().setTextFormat(tf); } private function init3():void { textArea3.htmlText = "<TEXTFORMAT TABSTOPS='100,200,300,400'><P>The quick<TAB/>brown fox<TAB/>jumps over<TAB/>the lazy<TAB/>dog.</P><P>The<TAB/>quick brown<TAB/>fox jumps<TAB/>over the<TAB/>lazy dog.</P></TEXTFORMAT>"; } private function init4():void { var tf:TextFormat = new TextFormat(); tf.tabStops = [100, 200, 300, 400]; textArea4.mx_internal::getTextField().defaultTextFormat = tf; textArea4.text = "The quick\\tbrown fox\\tjumps over\\tthe lazy\\tdog.\\nThe\\tquick brown\\tfox jumps\\tover the\\tlazy dog."; textArea4.validateNow(); trace(textArea4.htmlText); } ]]> </mx:Script> <mx:TextArea id="textArea1" condenseWhite="true" width="500" creationComplete="init1();"> <mx:htmlText> <![CDATA[ <p>The quick<tab/>brown fox<tab/>jumps over<tab/>the lazy<tab/>dog.</p><p>The<tab/>quick brown<tab/>fox jumps<tab/>over the<tab/>lazy dog.</p> ]]> </mx:htmlText> </mx:TextArea> <mx:TextArea id="textArea2" condenseWhite="true" width="500"> <mx:htmlText> <![CDATA[ <TEXTFORMAT TABSTOPS="100,200,300,400"><P>The quick<TAB/>brown fox<TAB/>jumps over<TAB/>the lazy<TAB/>dog.</P><P>The<TAB/>quick brown<TAB/>fox jumps<TAB/>over the<TAB/>lazy dog.</P></TEXTFORMAT> ]]> </mx:htmlText> </mx:TextArea> <mx:TextArea id="textArea3" condenseWhite="true" width="500" initialize="init3();" /> <mx:TextArea id="textArea4" width="500" initialize="init4();" /> </mx:Application>Peter
Flex 3 has the textHeight property now which does the same. However it is still not correct when using HTML Text. I suppose it’s because of the html tags used in the text which are not part of the visible text. It would be great if there was a solution to solve that problem!
Hi – im working on a project where i have to determin the number of lines and find the best fontsize in a multiline textarea.
When i try to get the number of lines as you show above, I somethimes get wrong values. I can se in flex that its 2 lines, and numLines give me 3 lines.
Any help of why this is happening? It happens even if a use callater after textchange or fontchange.
Really helpful example, I can end my search here. But I want to find a string of particular line, I am using TextArea, and have wordWrap=true, so using above code I can find number of line, but not the string contain each line.
Please help me.
Thanks
private function removeExcessLines():void
{
var numLines:int = this.textField.numLines;
if( numLines > numLinesAllowed )
{
var lines:Array = ObjectUtil.copy( this.textField.text ) .split(“\r”);
var lineCount:int = 0;
var lineIndex:int = 0;
var currentLine:String;
this.textField.text = ”;
while( lineCount 0 ) {
this.textField.text += currentLine;
lineCount++;
if( lineCount == 1 ) {
this.textField.text += ‘\r’;
}
if( lineCount == 2 ) {
this.selectionBeginIndex = this.length;
this.selectionEndIndex = this.length;
}
}
lineIndex++;
}
}
}
how to get number of lines in spark text area?
Hi,
That’s cool! Thanks.
May I know how to limit characters per line instead in a textarea and to be able to save the value entered as it is, meaning the space and empty lines are included in the array?
Been trying to figure that out.
Thanks.