'00.Flex,Flash,ActionScript'에 해당되는 글 131건

  1. 2013.07.05 Exporting a TextFlow object in Flex 4
  2. 2013.07.05 flex tlf editor demo
  3. 2013.07.05 SparkRichTextEditor
  4. 2013.07.05 Print DataGrid In Flex
  5. 2013.07.05 FlexPrintJob
  6. 2013.07.04 [펌]Flash CS3에서 Flex Component Skin 제작하기
  7. 2013.07.03 Printing multipage output
  8. 2013.07.03 PrintDataGrid,percentHeight and multipage layouts
  9. 2013.07.03 How to Export into PDF/ / Flex + PDF / Generate PDF From Flex
  10. 2013.07.03 Save file as PDF in flex
  11. 2013.06.26 Toggling draggable columns in a Flex DataGrid control
  12. 2013.06.26 Dragging rows between two different Flex DataGrid controls
  13. 2013.06.26 [펌] [FLEX] blazeDS개발환경 요약참조 사항.
  14. 2013.06.25 Flex Convert Date to String
  15. 2013.06.24 Integrating Adobe Flex and IBM WebSphere Portal
  16. 2013.06.03 flex Create menu from XML
  17. 2013.05.28 Setting the vertical gap between items in a Flex VBox container
  18. 2013.05.28 flex Using embedded fonts
  19. 2013.05.28 flex lineseries dotted line 1
  20. 2013.05.28 flex CartesianChart
  21. 2013.05.28 flex DateFormatter
  22. 2013.05.22 flex 학습용 동영상
  23. 2013.05.20 [펌] Deleting items in a List from an item renderer
  24. 2013.05.20 [펌] (flex) itemrenderer 안의 component들의 외부 접근방법
  25. 2013.05.13 flex ImageSnapshot.captureBitmapData()
  26. 2013.05.13 [펌] FLEX에 Embed된 Flash SWF파일과의 통신
  27. 2013.05.10 flex DateField 날짜관련 유틸~
  28. 2013.05.07 Flex 4 animate properties
  29. 2013.04.25 MXAdvancedDataGridItemRenderer mouse over 시 배경 않보이게
  30. 2013.04.24 [펌] DataGrid 전체 다시 그리지 않고 데이터만 갱신하기
반응형

Exporting a TextFlow object in Flex 4

By On July 25, 2009 · 28 Comments

The following example shows how you can export a TextFlow object in Flex 4 by using the TextConverter class (flashx.textLayout.conversion.TextConverter), and specifying HTML format, plain text format, or Text Layout Format.

Full code after the jump.

The following example(s) require Flash Player 10 and the Adobe Flex 4 SDK. To download the Adobe Flash Builder 4 trial, see http://www.adobe.com/products/flex/. To download the latest nightly build of the Flex 4 SDK, see http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.
For more information on getting started with Flex 4 and Flash Builder 4, see the official Adobe Flex Team blog.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/07/25/exporting-a-textflow-object-in-flex-4/ -->
<s:Application name="Spark_TextConverter_export_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo"
        xmlns:comps="comps.*">
    <s:layout>
        <s:VerticalLayout paddingLeft="20" paddingRight="20"
                paddingTop="20" paddingBottom="20" />
    </s:layout>
 
    <fx:Script>
        <![CDATA[
            import flashx.textLayout.conversion.ConversionType;
            import flashx.textLayout.conversion.TextConverter;
        ]]>
    </fx:Script>
 
    <comps:CustomEditor id="customEditor" />
 
    <s:HGroup>
        <s:Button id="htmlBtn"
                label="Export as HTML"
                click="debug.text = TextConverter.export(customEditor.editor.textFlow,
                                        TextConverter.HTML_FORMAT,
                                        ConversionType.STRING_TYPE).toString();" />
        <s:Button id="plainTxtBtn"
                label="Export as plain text"
                click="debug.text = TextConverter.export(customEditor.editor.textFlow,
                                        TextConverter.PLAIN_TEXT_FORMAT,
                                        ConversionType.STRING_TYPE).toString();" />
        <s:Button id="tlfBtn"
                label="Export as TLF"
                click="debug.text = TextConverter.export(customEditor.editor.textFlow,
                                        TextConverter.TEXT_LAYOUT_FORMAT,
                                        ConversionType.STRING_TYPE).toString();" />
    </s:HGroup>
 
    <s:TextArea id="debug" width="100%" height="100%" />
 
</s:Application>

View source is enabled in the following example.

And the custom rich text editor component, comps/CustomEditor.mxml, is as follows:

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/07/25/exporting-a-textflow-object-in-flex-4/ -->
<s:Panel name="CustomEditor"
         xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/halo"
        title="SimpleTextEditor" minWidth="400">
    <s:layout>
        <s:VerticalLayout gap="0" />
    </s:layout>
 
    <fx:Script>
        <![CDATA[
            import flashx.textLayout.conversion.ConversionType;
            import flashx.textLayout.conversion.TextConverter;
            import flash.text.engine.FontPosture;
            import flash.text.engine.FontWeight;
            import flashx.textLayout.formats.TextAlign;
            import flashx.textLayout.formats.TextDecoration;
            import flashx.textLayout.formats.TextLayoutFormat;
            import mx.events.ColorPickerEvent;
            import mx.events.FlexEvent;
            import spark.events.IndexChangeEvent;
 
            protected function editor_selectionChangeHandler(evt:FlexEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                fontDDL.selectedItem = txtLayFmt.fontFamily;
                sizeDDL.selectedItem = txtLayFmt.fontSize;
                boldBtn.selected = (txtLayFmt.fontWeight == FontWeight.BOLD);
                italBtn.selected = (txtLayFmt.fontStyle == FontPosture.ITALIC);
                underBtn.selected = (txtLayFmt.textDecoration == TextDecoration.UNDERLINE);
                colorCP.selectedColor = txtLayFmt.color;
                lineBtn.selected = txtLayFmt.lineThrough;
 
                switch (txtLayFmt.textAlign) {
                    case TextAlign.LEFT:
                        txtAlignBB.selectedIndex = 0;
                        break;
                    case TextAlign.CENTER:
                        txtAlignBB.selectedIndex = 1;
                        break;
                    case TextAlign.RIGHT:
                        txtAlignBB.selectedIndex = 2;
                        break;
                    case TextAlign.JUSTIFY:
                        txtAlignBB.selectedIndex = 3;
                        break;
                    default:
                        txtAlignBB.selectedIndex = -1;
                        break;
                }
            }
 
            protected function fontDDL_changeHandler(evt:IndexChangeEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.fontFamily = fontDDL.selectedItem;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function sizeDDL_changeHandler(evt:IndexChangeEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.fontSize = sizeDDL.selectedItem;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function boldBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.fontWeight = (txtLayFmt.fontWeight == FontWeight.BOLD) ? FontWeight.NORMAL : FontWeight.BOLD;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function italBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.fontStyle = (txtLayFmt.fontStyle == FontPosture.ITALIC) ? FontPosture.NORMAL : FontPosture.ITALIC;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function underBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.textDecoration = (txtLayFmt.fontStyle == TextDecoration.UNDERLINE) ? TextDecoration.NONE : TextDecoration.UNDERLINE;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function colorCP_changeHandler(evt:ColorPickerEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.color = colorCP.selectedColor;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function txtAlignBB_changeHandler(evt:IndexChangeEvent):void {
                if (txtAlignBB.selectedItem) {
                    var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                        editor.selectionAnchorPosition,
                                        editor.selectionActivePosition);
                    txtLayFmt.textAlign = txtAlignBB.selectedItem.value;
                    editor.setFormatOfRange(txtLayFmt,
                                        editor.selectionAnchorPosition,
                                        editor.selectionActivePosition);
                    editor.setFocus();
                }
            }
 
            protected function lineBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.lineThrough = lineBtn.selected;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
        ]]>
    </fx:Script>
 
    <s:TextArea id="editor"
            focusEnabled="false"
            width="100%" height="100%"
            minHeight="200"
            selectionChange="editor_selectionChangeHandler(event);">
        <s:textFlow>
            <s:TextFlow paragraphSpaceBefore="20">
                <s:p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis et nibh lorem. Nulla ut velit magna. Nunc quis libero ac orci porta tincidunt eget in lorem. Aenean vitae nisi vitae urna lacinia congue. Duis nec leo turpis. Phasellus dui orci, lacinia in dictum lacinia, ullamcorper a tortor. Suspendisse lacinia, turpis vel euismod gravida, turpis dui vulputate libero, vel consequat enim sem nec mauris. Curabitur vitae magna vel neque accumsan commodo vitae quis ipsum. Nullam ac condimentum elit. Integer eget magna ac mi fermentum luctus. Ut pharetra auctor pulvinar. Duis lobortis, nulla at vestibulum tincidunt, ante neque scelerisque risus, ac dignissim nunc nisl rhoncus risus. Cras pretium egestas purus, a commodo nunc vehicula at. Fusce vestibulum enim in mi hendrerit a viverra justo tempor. Maecenas eget ipsum ac mauris dictum congue eu id justo.</s:p>
                <s:p>Aliquam tincidunt tempor nisi id porta. Aenean risus dolor, tincidunt a ultrices in, laoreet eu ante. Mauris vel lacus neque, ut scelerisque eros. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec vel lacus sit amet erat vehicula malesuada id in augue. Sed purus massa, placerat non imperdiet nec, venenatis a nulla. Donec vel ligula leo, in rhoncus arcu. Duis semper bibendum facilisis. Duis nibh lorem, egestas rutrum tincidunt non, vulputate accumsan nulla. Nunc ligula nisl, ultrices ut tempor quis, rutrum et enim. Nullam accumsan scelerisque ante id pretium. Mauris nibh metus, blandit in varius congue, pharetra sit amet sem. Phasellus tincidunt lacus quis est semper ut rhoncus sem pretium. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pulvinar, enim eu consectetur venenatis, dui tortor commodo ante, sit amet sagittis libero odio cursus neque. Aliquam a dui non eros placerat euismod. In at mattis felis. Suspendisse potenti. Morbi posuere condimentum lacus. Suspendisse tellus magna, viverra ac mattis vel, adipiscing eget lectus.</s:p>
                <s:p>Etiam ut eros lectus. Praesent nec massa nibh. Cras venenatis, ligula in condimentum euismod, nisl lorem hendrerit lacus, a imperdiet odio est et odio. Suspendisse eu orci ut augue commodo gravida sed eu risus. Vestibulum venenatis erat ac metus ullamcorper blandit. Integer et sem enim. Vivamus a arcu metus. Nunc sollicitudin commodo placerat. Maecenas vehicula, massa et auctor tempor, felis leo commodo lorem, eget pulvinar felis turpis nec erat. Mauris imperdiet gravida felis a eleifend.</s:p>
                <s:p>Suspendisse mattis tempor fringilla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed molestie arcu. Praesent ut tellus sed orci blandit tristique non eget est. Sed interdum feugiat nisi, sit amet aliquet enim sodales non. Maecenas in velit sit amet tellus tincidunt dapibus. Vivamus est eros, iaculis et venenatis a, malesuada vel lacus. Aliquam vel orci tortor. Etiam ornare ante eget massa dignissim a auctor nunc pellentesque. Pellentesque sodales porta nisi, pretium accumsan eros tincidunt vitae. Cras facilisis accumsan purus ultricies lacinia. Praesent consequat elit imperdiet tellus vehicula ut ornare mauris mattis. Suspendisse non tortor nisl. Etiam ac pretium est.</s:p>
                <s:p>Maecenas tristique, velit aliquam faucibus ornare, justo erat porta elit, sed venenatis neque mi ac elit. Nullam enim metus, gravida ac euismod sit amet, commodo vitae elit. Quisque eget molestie ante. Nulla fermentum pretium augue non tristique. Praesent in orci eu diam ultrices sodales ac quis leo. Aliquam lobortis elit quis mi rutrum feugiat. Aenean sed elit turpis. Duis enim ligula, posuere sit amet semper a, pretium vel leo. Etiam mollis dolor nec elit suscipit imperdiet. Sed a est eros.</s:p>
            </s:TextFlow>
        </s:textFlow>
    </s:TextArea>
    <mx:ControlBar width="100%" cornerRadius="0">
        <mx:ToolBar width="100%" horizontalGap="5">
            <s:DropDownList id="fontDDL"
                    width="150"
                    change="fontDDL_changeHandler(event);">
                <s:dataProvider>
                    <s:ArrayList source="[Arial,Verdana,Times New Roman,Trebuchet MS]" />
                </s:dataProvider>
            </s:DropDownList>
            <s:DropDownList id="sizeDDL"
                    width="60"
                    change="sizeDDL_changeHandler(event);">
                <s:dataProvider>
                    <s:ArrayList source="[8,10,12,14,16,24,36,72]" />
                </s:dataProvider>
            </s:DropDownList>
            <s:ToggleButton id="boldBtn"
                    label="B"
                    fontWeight="bold"
                    width="30"
                    click="boldBtn_clickHandler(event);" />
            <s:ToggleButton id="italBtn"
                    label="I"
                    fontStyle="italic"
                    width="30"
                    click="italBtn_clickHandler(event);" />
            <s:ToggleButton id="underBtn"
                    label="U" 
                    textDecoration="underline"
                    width="30"
                    click="underBtn_clickHandler(event);" />
            <s:ToggleButton id="lineBtn"
                    label="S"
                    lineThrough="true"
                    width="30"
                    click="lineBtn_clickHandler(event);" />
            <mx:ColorPicker id="colorCP"
                    change="colorCP_changeHandler(event);" />
            <s:ButtonBar id="txtAlignBB"
                    arrowKeysWrapFocus="true"
                    labelField="label"
                    width="120"
                    change="txtAlignBB_changeHandler(event);">
                <s:dataProvider>
                    <s:ArrayList>
                        <fx:Object label="L" value="{TextAlign.LEFT}" />
                        <fx:Object label="C" value="{TextAlign.CENTER}" />
                        <fx:Object label="R" value="{TextAlign.RIGHT}" />
                        <fx:Object label="J" value="{TextAlign.JUSTIFY}" />
                    </s:ArrayList>
                </s:dataProvider>
            </s:ButtonBar>
        </mx:ToolBar>
    </mx:ControlBar>
 
</s:Panel>

This entry is based on a beta version of the Flex 4 SDK and therefore is very likely to change as development of the Flex SDK continues. The API can (and will) change causing examples to possibly not compile in newer versions of the Flex 4 SDK.

 

Posted by 1010
반응형
Posted by 1010
반응형

SparkRichTextEditor is a flex component based on Text Layout Framework with basic functionality implementation of a simple text editor with styles and key shortcuts with advances and improvements of new text system of Adobe.

Source codeClick with the right button to obtain source code.

More great examples of Adobe TLF and from tlftexteditor (in Google Code).

Posted by 1010
반응형

Print DataGrid In Flex


PrintDataGridExample.mxml

<?xml version="1.0"?>
<!-- Main application to print a DataGrid control on multiple pages. -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="initData();">
<mx:Script>
<![CDATA[
import mx.printing.*;
import mx.collections.ArrayCollection;
import FormPrintView;

// Declare variables and initialize simple variables.
[Bindable]
public var dgProvider:ArrayCollection;
public var footerHeight:Number=20;
public var prodIndex:Number;
public var prodTotal:Number=0;

// Data initialization.
public function initData():void
{
// Create the data provider for the DataGrid control.
dgProvider=new ArrayCollection;
}

// Fill the dgProvider ArrayCollection with the specified items.
public function setdgProvider(items:int):void
{

prodIndex=1;
dgProvider.removeAll();
for (var z:int=0; z < items; z++)
{
var prod1:Object={};
prod1.Qty=prodIndex * 7;
prod1.Index=prodIndex++;
prodTotal+=prod1.Qty;
dgProvider.addItem(prod1);
}
}

// The function to print the output.
public function doPrint():void
{

var printJob:FlexPrintJob=new FlexPrintJob();
if (printJob.start())
{
// Create a FormPrintView control as a child of the current view.
var thePrintView:FormPrintView=new FormPrintView();
Application.application.addChild(thePrintView);

//Set the print view properties.
thePrintView.width=printJob.pageWidth;
thePrintView.height=printJob.pageHeight;
thePrintView.prodTotal=prodTotal;
// Set the data provider of the FormPrintView component's data grid
// to be the data provider of the displayed data grid.
thePrintView.myDataGrid.dataProvider=myDataGrid.dataProvider;
// Create a single-page image.
thePrintView.showPage("single");
// If the print image's data grid can hold all the provider's rows,
// add the page to the print job.
if (!thePrintView.myDataGrid.validNextPage)
{
printJob.addObject(thePrintView);
}
// Otherwise, the job requires multiple pages.
else
{
// Create the first page and add it to the print job.
thePrintView.showPage("first");
printJob.addObject(thePrintView);
thePrintView.pageNumber++;
// Loop through the following code until all pages are queued.
while (true)
{
// Move the next page of data to the top of the print grid.
thePrintView.myDataGrid.nextPage();
thePrintView.showPage("last");
// If the page holds the remaining data, or if the last page
// was completely filled by the last grid data, queue it for printing.
// Test if there is data for another PrintDataGrid page.
if (!thePrintView.myDataGrid.validNextPage)
{
// This is the last page; queue it and exit the print loop.
printJob.addObject(thePrintView);
break;
}
else
// This is not the last page. Queue a middle page.
{
thePrintView.showPage("middle");
printJob.addObject(thePrintView);
thePrintView.pageNumber++;
}
}
}
// All pages are queued; remove the FormPrintView control to free memory.
Application.application.removeChild(thePrintView);
}
// Send the job to the printer.
printJob.send();
}
]]>
</mx:Script>

<mx:Panel title="DataGrid Printing Example" height="75%" width="75%" paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10">

<mx:DataGrid id="myDataGrid" dataProvider="{dgProvider}">
<mx:columns>
<mx:DataGridColumn dataField="Index"/>
<mx:DataGridColumn dataField="Qty"/>
</mx:columns>
</mx:DataGrid>

<mx:Text width="100%" color="blue" text="Specify the number of lines and click Fill Grid first. Then you can click Print."/>

<mx:TextInput id="dataItems" text="35"/>

<mx:HBox>
<mx:Button id="setDP" label="Fill Grid" click="setdgProvider(int(dataItems.text));"/>
<mx:Button id="printDG" label="Print" click="doPrint();"/>
</mx:HBox>
</mx:Panel>
</mx:Application>


FormPrintView.mxml

<?xml version="1.0"?>
<!-- Custom control to print the DataGrid control on multiple pages. -->

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" backgroundColor="#FFFFFF" paddingTop="50" paddingBottom="50" paddingLeft="50">

<mx:Script>
<![CDATA[
import mx.core.*
// Declare and initialize the variables used in the component.
// The application sets the actual prodTotal value.
[Bindable]
public var pageNumber:Number=1;
[Bindable]
public var prodTotal:Number=0;

// Control the page contents by selectively hiding the header and
// footer based on the page type.
public function showPage(pageType:String):void
{
if (pageType == "first" || pageType == "middle")
{
// Hide the footer.
footer.includeInLayout=false;
footer.visible=false;
}
if (pageType == "middle" || pageType == "last")
{
// The header won't be used again; hide it.
header.includeInLayout=false;
header.visible=false;
}
if (pageType == "last")
{
// Show the footer.
footer.includeInLayout=true;
footer.visible=true;
}
//Update the DataGrid layout to reflect the results.
validateNow();
}
]]>
</mx:Script>

<!-- The template for the printed page, with the contents for all pages. -->
<mx:VBox width="80%" horizontalAlign="left">
<mx:Label text="Page {pageNumber}"/>
</mx:VBox>

<FormPrintHeader id="header"/>
<!-- The data grid. The sizeToPage property is true by default, so the last
page has only as many grid rows as are needed for the data. -->
<mx:PrintDataGrid id="myDataGrid" width="60%" height="100%">
<!-- Specify the columns to ensure that their order is correct. -->
<mx:columns>
<mx:DataGridColumn dataField="Index"/>
<mx:DataGridColumn dataField="Qty"/>
</mx:columns>
</mx:PrintDataGrid>

<!-- Create a FormPrintFooter control and set its prodTotal variable. -->
<FormPrintFooter id="footer" pTotal="{prodTotal}"/>

</mx:VBox>


FormPrintHeader.mxml

<?xml version="1.0"?>
<!-- Custom control for the header area of the printed page. -->

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="60%" horizontalAlign="right">

<mx:Label text="This is a placeholder for first page contents"/>
</mx:VBox>


FormPrintFooter.mxml

<?xml version="1.0"?>
<!-- Custom control for the footer area of the printed page. -->

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="60%" horizontalAlign="right">
<!-- Declare and initialize the product total variable. -->

<mx:Script>
<![CDATA[
[Bindable]
public var pTotal:Number=0;
]]>
</mx:Script>
<mx:Label text="Product Total: {pTotal}"/>
</mx:VBox>


Examples:-

Posted by 1010
반응형
FlexPrintJob

패키지 mx.printing
클래스 public class FlexPrintJob
상속 FlexPrintJob Inheritance Object

언어 버전:  ActionScript 3.0
제품 버전:  Flex 3
런타임 버전:  Flash Player 9, AIR 1.1

 

Was this helpful?Yes   No

 

 

The FlexPrintJob class is a wrapper for the flash.printing.PrintJob class. It supports automatically slicing and paginating the output on multilple pages, and scaling the grid contents to fit the printer's page size.

 

예제 보기

기타 예제

추가 정보


 


공용 속성
  속성 정의 주체
  Inherited constructor : Object
지정된 객체 인스턴스의 클래스 객체 또는 생성자 함수에 대한 참조입니다.
Object
    pageHeight : Number
[읽기 전용] The height of the printable area on the printer page; it does not include any user-set margins.
FlexPrintJob
    pageWidth : Number
[읽기 전용] The width of the printable area on the printer page; it does not include any user-set margins.
FlexPrintJob
    printAsBitmap : Boolean
Specifies whether to print the job content as a bitmap (true) or in vector format (false).
FlexPrintJob
공용 메서드
  메서드 정의 주체
   
Constructor.
FlexPrintJob
   
addObject(obj:IUIComponent, scaleType:String = "matchWidth"):void
Adds a UIComponent object to the list of objects being printed.
FlexPrintJob
  Inherited
지정된 속성이 객체에 정의되어 있는지 여부를 나타냅니다.
Object
  Inherited
Object 클래스의 인스턴스가 매개 변수로 지정된 객체의 프로토타입 체인에 있는지 여부를 나타냅니다.
Object
  Inherited
지정된 속성이 존재하고 열거 가능한지 여부를 나타냅니다.
Object
   
Sends the added objects to the printer to start printing.
FlexPrintJob
  Inherited
루프 작업에서 동적 속성을 사용할 수 있는지 여부를 설정합니다.
Object
   
Initializes the PrintJob object.
FlexPrintJob
  Inherited
로캘별 규칙에 따라 서식이 지정된 이 객체의 문자열 표현을 반환합니다.
Object
  Inherited
지정된 객체의 문자열 표현을 반환합니다.
Object
  Inherited
지정된 객체의 프리미티브 값을 반환합니다.
Object
속성 세부 정보

pageHeight

속성
pageHeight:Number  [읽기 전용]

 

언어 버전:  ActionScript 3.0
제품 버전:  Flex 3
런타임 버전:  Flash Player 9, AIR 1.1

 

 

The height of the printable area on the printer page; it does not include any user-set margins. It is set after start() method returns.



구현
    public function get pageHeight():Number

pageWidth

속성  
pageWidth:Number  [읽기 전용]

 

언어 버전:  ActionScript 3.0
제품 버전:  Flex 3
런타임 버전:  Flash Player 9, AIR 1.1

 

 

The width of the printable area on the printer page; it does not include any user-set margins. This property is set after start() method returns.



구현
    public function get pageWidth():Number

printAsBitmap

속성  
printAsBitmap:Boolean

언어 버전:  ActionScript 3.0
제품 버전:  Flex 3
런타임 버전:  Flash Player 9, AIR 1.1

 

 

Specifies whether to print the job content as a bitmap (true) or in vector format (false). Printing as a bitmap supports output that includes a bitmap image with alpha transparency or color effects. If the content does not include any bitmap images with alpha transparency or color effects, you can print in higher quality vector format by setting the printAsBitmap property to false.

기본값: true.



구현
    public function get printAsBitmap():Boolean
    public function set printAsBitmap(value:Boolean):void
생성자 세부 정보

FlexPrintJob

() 생성자
public function FlexPrintJob()

 

언어 버전:  ActionScript 3.0
제품 버전:  Flex 3
런타임 버전:  Flash Player 9, AIR 1.1

 

Constructor.

메서드 세부 정보

addObject

() 메서드
public function addObject(obj:IUIComponent, scaleType:String = "matchWidth"):void

언어 버전:  ActionScript 3.0
제품 버전:  Flex 3
런타임 버전:  Flash Player 9, AIR 1.1

 

 

Adds a UIComponent object to the list of objects being printed. Call this method after the start() method returns. Each call to this method starts a new page, so you should format your objects in page-sized chunks. You can use the PrintDataGrid class to span a data grid across multiple pages.

매개 변수

obj:IUIComponent — The Object to be printed.
 
scaleType:String (default = "matchWidth") — The scaling technique to use to control how the object fits on one or more printed pages. Must be one of the constant values defined in the FlexPrintJobScaleType class.

 

관련 API 요소

send

() 메서드  
public function send():void

언어 버전:  ActionScript 3.0
제품 버전:  Flex 3
런타임 버전:  Flash Player 9, AIR 1.1

 

 

Sends the added objects to the printer to start printing. Call this method after you have used the addObject() method to add the print pages.

start

() 메서드  
public function start():Boolean

언어 버전:  ActionScript 3.0
제품 버전:  Flex 3
런타임 버전:  Flash Player 9, AIR 1.1

 

 

Initializes the PrintJob object. Displays the operating system printer dialog to the user. Flex sets the pageWidth and pageHeight properties after this call returns.

 

반환값
Booleantrue if the user clicks OK when the print dialog box appears, or false if the user clicks Cancel or if an error occurs.
FormPrintHeader.mxml
<?xml version="1.0"?>
<!-- Custom control for the header area of the printed page. -->
<s:VGroup name="FormPrintHeader"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        width="60%"
        horizontalAlign="right" >

    <s:Label text="This is a placeholder for first page contents"/>

</s:VGroup>
FormPrintFooter.mxml
<?xml version="1.0"?>
<!-- Custom control for the footer area of the printed page. -->
<s:VGroup name="FormPrintFooter"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        width="60%"
        horizontalAlign="right" >

    <!-- Declare and initialize the product total variable. -->
    <fx:Script>
        <![CDATA[
            [Bindable]
            public var pTotal:Number = 0;
        ]]>
    </fx:Script>

    <s:Label text="Product Total: {pTotal}"/>

</s:VGroup>
FormPrintView.mxml
<?xml version="1.0"?>
<!-- Custom control to print the Halo DataGrid control on multiple pages. -->
<s:VGroup name="FormPrintView"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/mx"
        xmlns="*">

    <fx:Script>
        <![CDATA[
            import mx.core.*;

            // Declare and initialize the variables used in the component.
            // The application sets the actual prodTotal value.
            [Bindable]
            public var pageNumber:Number = 1;

            [Bindable]
            public var prodTotal:Number = 0;

            // Control the page contents by selectively hiding the header and
            // footer based on the page type.
            public function showPage(pageType:String):void {
                if (pageType == "first" || pageType == "middle") {
                    // Hide the footer.
                    footer.includeInLayout = false;
                    footer.visible = false;
                }
                if (pageType == "middle" || pageType == "last") {
                    // The header won't be used again; hide it.
                    header.includeInLayout = false;
                    header.visible = false;
                }
                if (pageType == "last") {
                    // Show the footer.
                    footer.includeInLayout = true;
                    footer.visible = true;
                }
                //Update the DataGrid layout to reflect the results.
                validateNow();
            }
        ]]>
    </fx:Script>

    <!-- The template for the printed page, with the contents for all pages. -->
    <s:VGroup width="80%" horizontalAlign="left">
        <s:Label text="Page {pageNumber}"/>
    </s:VGroup>

    <FormPrintHeader id="header" />

    <!-- The data grid. The sizeToPage property is true by default, so the last
        page has only as many grid rows as are needed for the data. -->
    <mx:PrintDataGrid id="myDataGrid" width="60%" height="100%">
        <!-- Specify the columns to ensure that their order is correct. -->
        <mx:columns>
            <mx:DataGridColumn dataField="Index" />
            <mx:DataGridColumn dataField="Qty" />
        </mx:columns>
    </mx:PrintDataGrid>

    <!-- Create a FormPrintFooter control and set its prodTotal variable. -->
    <FormPrintFooter id="footer" pTotal="{prodTotal}" />

</s:VGroup>
PrintDataGridExample.mxml
<?xml version="1.0"?>
<!-- Main application to print a Halo DataGrid control on multiple pages. -->
<s:Application name="PrintDataGridExample.mxml"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/mx"
        initialize="initData();">

    <fx:Script>
        <![CDATA[

        import mx.printing.*;
        import mx.collections.ArrayCollection;
        import FormPrintView;
        import mx.core.FlexGlobals;

        // Declare variables and initialize simple variables.
        [Bindable]
        public var dgProvider:ArrayCollection;
        public var footerHeight:Number = 20;
        public var prodIndex:Number;
        public var prodTotal:Number = 0;


        // Data initialization.
        public function initData():void {
            // Create the data provider for the DataGrid control.
            dgProvider = new ArrayCollection;
        }

        // Fill the dgProvider ArrayCollection with the specified items.
        public function setdgProvider(items:int):void {
            prodIndex=1;
            dgProvider.removeAll();
            for (var z:int=0; z<items; z++) {
                var prod1:Object = {};
                prod1.Qty = prodIndex * 7;
                prod1.Index = prodIndex++;
                prodTotal += prod1.Qty;
                dgProvider.addItem(prod1);
            }
        }

        // The function to print the output.
        public function doPrint():void {
            var printJob:FlexPrintJob = new FlexPrintJob();
            if (printJob.start()) {
                // Create a FormPrintView control as a child of the current view.
                var thePrintView:FormPrintView = new FormPrintView();
                FlexGlobals.topLevelApplication.addElement(thePrintView);

                //Set the print view properties.
                thePrintView.width=printJob.pageWidth;
                thePrintView.height=printJob.pageHeight;
                thePrintView.prodTotal = prodTotal;
                // Set the data provider of the FormPrintView component's data grid
                // to be the data provider of the displayed data grid.
                thePrintView.myDataGrid.dataProvider = myDataGrid.dataProvider;
                // Create a single-page image.
                thePrintView.showPage("single");
                // If the print image's data grid can hold all the provider's rows,
                // add the page to the print job.
                if (!thePrintView.myDataGrid.validNextPage)  {
                    printJob.addObject(thePrintView);
                }
                // Otherwise, the job requires multiple pages.
                else {
                    // Create the first page and add it to the print job.
                    thePrintView.showPage("first");
                    printJob.addObject(thePrintView);
                    thePrintView.pageNumber++;
                    // Loop through the following code until all pages are queued.
                    while (true) {
                        // Move the next page of data to the top of the print grid.
                        thePrintView.myDataGrid.nextPage();
                        thePrintView.showPage("last");
                        // If the page holds the remaining data, or if the last page
                        // was completely filled by the last grid data, queue it for printing.
                        // Test if there is data for another PrintDataGrid page.
                        if (!thePrintView.myDataGrid.validNextPage) {
                            // This is the last page; queue it and exit the print loop.
                            printJob.addObject(thePrintView);
                            break;
                        } else {
                            // This is not the last page. Queue a middle page.
                            thePrintView.showPage("middle");
                            printJob.addObject(thePrintView);
                            thePrintView.pageNumber++;
                        }
                    }
                }
                // All pages are queued; remove the FormPrintView control to free memory.
                FlexGlobals.topLevelApplication.removeElement(thePrintView);
            }
            // Send the job to the printer.
            printJob.send();
        }
        ]]>
    </fx:Script>

    <s:Panel title="DataGrid Printing Example"
            width="75%" height="75%"
            horizontalCenter="0" verticalCenter="0">
        <s:VGroup left="10" right="10" top="10" bottom="10">
            <mx:DataGrid id="myDataGrid" dataProvider="{dgProvider}">
                <mx:columns>
                    <mx:DataGridColumn dataField="Index"/>
                    <mx:DataGridColumn dataField="Qty"/>
                </mx:columns>
            </mx:DataGrid>

            <s:Label width="100%" color="blue"
                text="Specify the number of lines and click Fill Grid first. Then you can click Print."/>

            <s:TextInput id="dataItems" text="35"/>

            <s:HGroup>
                <s:Button id="setDP" label="Fill Grid" click="setdgProvider(int(dataItems.text));"/>
                <s:Button id="printDG" label="Print" click="doPrint();"/>
            </s:HGroup>
        </s:VGroup>
    </s:Panel>

</s:Application>
Posted by 1010
반응형


Flash CS3에서 Flex Component Skin 제작하기

[출처] http://blog.naver.com/ang_/30029082083

자세한 제작 내용은 위 출처를 참고해주세요. 여기서는 Flex Skin Templetes 자료와 준비 과정까지만을 포스팅 하겠습니다.

Flash CS3에서 Flex Component Skin을 제작하기 위해서는 직접 플래쉬로 구현하는 방법도 있겠지만 초보자들에겐 쉽지만은 않은 방법입니다. 그래서 좀 더 편한 방법으로 제공되어진게 바로 미리 제작되어진 Templetes를 이용하는 방법이 있습니다.

우선 제작하기 위해선 flex skin 파일을 다운로드 받으셔야 합니다.
다운로드 - http://www.adobe.com/cfusion/entitlement/index.cfm?e=flex_skins#fxcompkit

위 사이트로 가시면 Flex Skin Design Extension for Flash에 있는 파일을 다운받으시기 바랍니다.

dlDownload for Windows and Macintosh (MXP, 4.44 MB) <--- 귀찮으신 분들은 여기를 클릭


(링크가 깨졌을 경우 아래 링크로 다운받으세요.)



를 다운 받으셨으면 이제 CS3 Extension Manager를 실행합니다.
Extension Manager은 아래 경로에 존재합니다.
C:\Program Files\Adobe\Adobe Extension Manager\Extension Manager.exe
Adobe Master Collection CS3 을 설치 하신 분들이라면
시작 → 모든프로그램 → Adobe Master Collection CS3 → Adobe Extension Manager CS3

(다운로드 받은 파일을 더블클릭하시면 자동으로 Extension Manager가 실행 되지만 만약 CS4를 같이 설치하신분이라면
CS4용 Adobe Extension Manager가 실행 되니 위에 나와있는 방법으로 실행하시면 됩니다.)


Extension Manager를 실행하시면 위와 같은 실행화면을 보실 수 있습니다.
 버튼을 클릭하여 다운받은
 파일을 선택하여 줍니다.


동의 창이 나오면 동의버튼을
  클릭합니다.


설치 화면이 나오고 설치 성공 화면이 나오면 확인 버틍을 클릭합니다.



Extension Manager를 종료하고 Flash CS3를 실행 시킵니다.



위 처럼 Flex Skins 라는 메뉴가 나오면 스킨 만들 준비 끝~~
그럼 이제 스킨 템플릿 파일을 열어 보겠습니다.


위와 같이 여러 콤포넌트들의 스킨을 제작할 수 있습니다.
여기서 flex_skins 파일을 선택합니다.


flex의 기본 콤포넌트의 스킨들이 모두 모아져 있습니다. 여기서 스킨을 수정 하여 swc 파일로 Export 시키셔서 flex에서 사용하시면 됩니다. 제작법과 flex에서 불러오는 법은 행복한앙님의 블로그에 자세히 나와 있으니 참고 하시기 바랍니다.
행복한앙님 블로그의 게시물 : http://blog.naver.com/ang_/30029082083

 

Posted by 1010
반응형

Adobe Flex 3 Help

Printing multipage output

You can print well-formatted multipage output under the following conditions:

  • When each control fits on a print page or less. You often encounter such jobs when printing a form with fixed-length fields.
  • When the printed output includes one or more PrintDataGrid controls that are too long to print on a single page, particularly if the control height might vary, depending on the data. A good example of this type of output is a customer order receipt, which starts with the customer information, has an indeterminate number of order line items, and ends with total information.

Printing known-length multipage output

If you know the length of each component in a multipage document, you can create a separate print layout component for each page you print, and specify each layout page in a separate addObject() method, as follows:

printJob.addObject(introPrintView, "ShowAll");
printJob.addObject(finDetailPrintView, "ShowAll");
printJob.addObject(hrDetailPrintView, "ShowAll");
printJob.addObject(summaryPrintView, "ShowAll");

Using the PrintDataGrid control for multipage grids

When a DataGrid control with many rows does not fit on a single screen in your application, you typically have scroll bars that let users view all the data. When you print the DataGrid control, the output is the same as the screen display. Therefore, if your DataGrid control has rows or columns that are not immediately visible, they do not print. If you replace the DataGrid control with a PrintDataGrid control that does not have a height specified (or has a large height), you print all the rows, but some rows could be partially printed on the bottom of one page and partially printed at the top of another, as you often see with HTML printout.

You can solve these problems by using the following features of the PrintDataGrid control. These features let you correctly print grids that contain multiple pages of data without splitting rows across pages:

sizeToPage property 

Makes the printed data grid contain only full rows.



nextPage() method 

Gets the next printable page of data.



validNextPage property 

Is true if printing the data requires an additional page.



Using the sizeToPage attribute to format pages

A PrintDataGrid page consists of the rows that are visible in the control's current view. Suppose, for example, that a PrintDataGrid control has a height of 130 pixels. The total height of each row and header is 30 pixels, and the control's data provider has 10 rows. In this situation, the printed PrintDataGrid page contains only three complete data rows, plus the header. The sizeToPage property specifies whether to include a fourth and partial data row.

The sizeToPage property, which is true by default, causes the PrintDataGrid control to remove any partially visible or empty rows and to resize itself to include only complete rows in the current view. For the data grid described in the preceding paragraph, when this property is true, the DataGrid shrinks to show three complete data rows, and no incomplete rows; if the attribute is false, the grid includes a partial row at the bottom.

The following properties provide information on page sizing that are affected by the sizeToPage property:

Property

Description

currentPageHeight

Contains the height of the grid, in pixels, that results if the sizeToPage property is true. If the sizeToPage property is true, the currentPageHeight property equals the height property.

originalHeight

Contains the grid height that results if the sizeToPage property is false. If the sizeToPage property is false, the originalHeight property equals the height property.

In most applications, you leave the sizeToPage attribute at its default value (true), and use the height property to determine the grid height.

The sizeToPage property does not affect the way the page breaks when a single PrintDataGrid control page is longer than a print page. To print multipage data grids without splitting rows, you must divide the grid items into multiple views by using the nextPage() method, as described in Using the nextPage() method and validNextPage property to print multiple pages.

Using the nextPage() method and validNextPage property to print multiple pages

The validNextPage property is true if the PrintDataGrid control has data beyond the rows that fit on the current print page. You use it to determine whether you need to format and print an additional page.

The nextPage() method lets you page through the data provider contents by setting the first row of the PrintDataGrid control to be the data provider row that follows the last row of the previous PrintDataGrid page. In other words, the nextPage() method increases the grid's verticalScrollPosition property by the value of the grid's rowCount property.

The following code shows a loop that prints a grid using multiple pages, without having rows that span pages:

// Queue the first page.
printJob.addObject(thePrintView);
// While there are more pages, print them.
while (thePrintView.myDataGrid.validNextPage) {
    //Put the next page of data in the view.
    thePrintView.myDataGrid.nextPage();
    //Queue the additional page.
    printJob.addObject(thePrintView);
}

The section Example: Printing with multipage PrintDataGrid controls shows how to use the nextPage() method to print a report with a multipage data grid.

Updating the PrintDataGrid layout

When you use a PrintDataGrid control to print a single data grid across multiple pages, you queue each page of the grid individually. If your application customizes each page beyond simply using the nextPage() method to page through the PrintDataGrid, you must call the validateNow() method to update the page layout before you print each page, as shown in Print output component.

Example: Printing with multipage PrintDataGrid controls

The following example prints a data grid in which you can specify the number of items in the data provider. You can, therefore, set the DataGrid control contents to print on one, two, or more pages, so that you can see the effects of different-sized data sets on the printed result.

The example also shows how you can put header information before the grid and footer information after the grid, as in a shipping list or receipt. It uses the technique of selectively showing and hiding the header and footer, depending on the page being printed. To keep the code as short as possible, the example uses simple placeholder information only.

The application consists of the following files:

  • The application file displays the form to the user, including TextArea and Button controls to set the number of lines and a Print button. The file includes the code to initialize the view, get the data, and handle the user's print request. It uses the FormPrintView MXML component as a template for the printed output.
  • The FormPrintView.mxml file formats the printed output. It has two major elements:
    • The print output template includes the PrintDataGrid control and uses two MXML components to format the header and footer contents.
    • The showPage() function determines which sections of the template to include in a particular page of the output, based on the page type: first, middle, last, or single. On the first page of multipage output, the showPage() function hides the footer; on the middle and last pages, it hides the header. On a single page, it shows both header and footer.
  • The FormPrintHeader.mxml and formPrintFooter.mxml files specify the contents of the start and the end of the output. To keep the application simple, the header has a single, static Label control. The footer displays a total of the numbers in the Quantity column. In a more complete application, the header page could have, for example, a shipping address, and the footer page could show more detail about the shipment totals.

The files include detailed comments explaining the purpose of the code.

Multipage print application file

The following code shows the multipage print application file:

<?xml version="1.0"?>
<!-- printing\MultiPagePrint.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    initialize="initData();">

    <mx:Script>
    <![CDATA[
        import mx.printing.*;
        import mx.collections.ArrayCollection;
        // Import the MXML custom print view control.
        import myComponents.FormPrintView;

        // Declare variables and initialize simple variables.
        // The dgProvider ArrayCollection is the DataGrid data provider.
        // It must be bindable because you change its contents dynamically.
        [Bindable]
        public var dgProvider:ArrayCollection;
        public var footerHeight:Number = 20;
        public var prodIndex:Number;
        public var prodTotal:Number = 0;
        
        // Data initialization, called when the application initializes.
        public function initData():void {
            // Create the data provider for the DataGrid control.
            dgProvider = new ArrayCollection; 
        }
        
        // Fill the dgProvider ArrayCollection with the specified items.
        public function setdgProvider(items:int):void { 
            // First initialize the index and clear any existing data.
            prodIndex=1;
            dgProvider.removeAll();
            
            // Fill the ArrayCollection, and calculate a product total.
            // For simplicity, it increases the Index field value by
            // 1, and the Qty field by 7 for each item.
            for (var z:int=0; z<items; z++) 
            {
                var prod1:Object = {};
                prod1.Qty = prodIndex * 7;
                prod1.Index = prodIndex++;
                prodTotal += prod1.Qty; 
                dgProvider.addItem(prod1);
            }
        }

        // The function to print the output.
        public function doPrint():void {
            // Create a FlexPrintJob instance.
            var printJob:FlexPrintJob = new FlexPrintJob();
            
            // Start the print job.
            if (printJob.start()) {
                // Create a FormPrintView control 
                // as a child of the application.
                var thePrintView:FormPrintView = new FormPrintView();
                addChild(thePrintView);
                
                // Set the print view properties.
                thePrintView.width=printJob.pageWidth;
                thePrintView.height=printJob.pageHeight;
                thePrintView.prodTotal = prodTotal;
                
                // Set the data provider of the FormPrintView 
                // component's DataGrid to be the data provider of 
                // the displayed DataGrid.
                thePrintView.myDataGrid.dataProvider = 
                    myDataGrid.dataProvider;
                
                // Create a single-page image.
                thePrintView.showPage("single");
                
                // If the print image's DataGrid can hold all the  
                // data provider's rows, add the page to the print job. 
                if(!thePrintView.myDataGrid.validNextPage)
                {
                    printJob.addObject(thePrintView);
                }
                // Otherwise, the job requires multiple pages.
                else
                {
                    // Create the first page and add it to the print job.
                    thePrintView.showPage("first");
                    printJob.addObject(thePrintView);
                    thePrintView.pageNumber++;
                    
                    // Loop through the following code 
                    // until all pages are queued.
                    while(true)
                    {
                        // Move the next page of data to the top of 
                        // the PrintDataGrid.
                        thePrintView.myDataGrid.nextPage();

                        // Try creating a last page.
                        thePrintView.showPage("last");  

                        // If the page holds the remaining data, or if 
                        // the last page was completely filled by the last  
                        // grid data, queue it for printing.
                        // Test if there is data for another 
                        // PrintDataGrid page.
                        if(!thePrintView.myDataGrid.validNextPage) 
                        {
                            // This is the last page; 
                            // queue it and exit the print loop.
                            printJob.addObject(thePrintView);
                            break;
                        }
                        else
                        // This is not the last page. Queue a middle page. 
                        {
                            thePrintView.showPage("middle");
                            printJob.addObject(thePrintView);
                            thePrintView.pageNumber++;
                        }
                    }
                }
                // All pages are queued; remove the FormPrintView 
                // control to free memory.
                removeChild(thePrintView);
            }
            // Send the job to the printer.
            printJob.send();
        }
    ]]>
    </mx:Script>

    <!-- The form that appears on the user's system.-->
    <mx:Form id="myForm" width="80%">
        <mx:FormHeading label="Product Information"/>
                <mx:DataGrid id="myDataGrid" dataProvider="{dgProvider}">
                <mx:columns>
                    <mx:DataGridColumn dataField="Index"/>
                    <mx:DataGridColumn dataField="Qty"/>
                </mx:columns>
            </mx:DataGrid>
        <mx:Text width="100%" 
            text="Specify the number of lines and click Fill Grid first. 
            Then you can click Print."/>
        <mx:TextInput id="dataItems" text="35"/>
        <mx:HBox>
            <mx:Button id="setDP" 
                label="Fill Grid"
                click="setdgProvider(int(dataItems.text));"/>
            <mx:Button id="printDG" 
                label="Print" 
                click="doPrint();"/>
        </mx:HBox>
    </mx:Form>
</mx:Application>

The executing SWF file for the previous example is shown below:

 

Print output component

The following lines show the FormPrintView.mxml custom component file:

<?xml version="1.0"?>
<!-- printing\myComponents\FormPrintView.mxml -->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:MyComp="myComponents.*" 
    backgroundColor="#FFFFFF"
    paddingTop="50" paddingBottom="50" paddingLeft="50">

    <mx:Script>
        <![CDATA[
            import mx.core.*
            
            // Declare and initialize the variables used in the component.
            // The application sets the actual prodTotal value.
            [Bindable]
            public var pageNumber:Number = 1;
            [Bindable]
            public var prodTotal:Number = 0;

            // Control the page contents by selectively hiding the header and
            // footer based on the page type.
            public function showPage(pageType:String):void {
                if(pageType == "first" || pageType == "middle") {
                    // Hide the footer.
                    footer.includeInLayout=false;
                    footer.visible = false;
                }
                if(pageType == "middle" || pageType == "last") {
                    // The header won't be used again; hide it.
                    header.includeInLayout=false;
                    header.visible = false;
                }
                if(pageType == "last") {
                    // Show the footer.
                    footer.includeInLayout=true;
                    footer.visible = true;
                }
                //Update the DataGrid layout to reflect the results.
                validateNow();
            }
        ]]>
    </mx:Script>

    <!-- The template for the printed page, 
        with the contents for all pages. -->
    <mx:VBox width="80%" horizontalAlign="left">
        <mx:Label text="Page {pageNumber}"/>
    </mx:VBox>
    <MyComp:FormPrintHeader id="header"/>
    
    <!-- The sizeToPage property is true by default, so the last
        page has only as many grid rows as are needed for the data. -->
    <mx:PrintDataGrid id="myDataGrid" width="60%" height="100%">
    <!-- Specify the columns to ensure that their order is correct. -->
        <mx:columns>
            <mx:DataGridColumn dataField="Index" />
            <mx:DataGridColumn dataField="Qty" />
        </mx:columns>
    </mx:PrintDataGrid>
    
    <!-- Create a FormPrintFooter control 
        and set its prodTotal variable. -->
    <MyComp:FormPrintFooter id="footer" pTotal="{prodTotal}"/>
</mx:VBox>

Header and footer files

The following lines show the FormPrintHeader.mxml file.

<?xml version="1.0"?>
<!-- printing\myComponents\FormPrintHeader.mxml -->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" 
    width="60%"
    horizontalAlign="right" >

    <mx:Label text="This is a placeholder for first page contents"/>
</mx:VBox>

The following lines show the FormPrintFooter.mxml file:

<?xml version="1.0"?>
<!-- printing\myComponents\FormPrintFooter.mxml -->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" 
    width="60%"
    horizontalAlign="right">
    
    <!-- Declare and initialize the product total variable. -->
    <mx:Script>
        <![CDATA[
            [Bindable]
            public var pTotal:Number = 0;
        ]]>
        </mx:Script>

    <mx:Label text="Product Total: {pTotal}"/>
</mx:VBox>

Using the PrintAdvancedDataGrid control

The PrintAdvancedDataGrid and PrintOLAPDataGrid controls provide the same functionality for the AdvancedDataGrid and OLAPDataGrid controls as the PrintDataGrid control does for the DataGrid control. For more information, see Using the PrintDataGrid control for multipage grids.

The following example uses the PrintAdvancedDataGrid control to print an instance of the AdvancedDataGrid control.

<?xml version="1.0"?>
<!-- printing\ADGPrint.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:Script>
        <![CDATA[
            import mx.printing.*;
            import mx.collections.ArrayCollection;
            import mx.printing.PrintAdvancedDataGrid;
                    
            include "SimpleHierarchicalData.as";

            // Create a PrintJob instance.
            private function doPrint():void {
                // Create an instance of the FlexPrintJob class.
                var printJob:FlexPrintJob = new FlexPrintJob();
                
                // Initialize the PrintAdvancedDataGrid control.
                var printADG:PrintAdvancedDataGrid = 
                    new PrintAdvancedDataGrid();
                // Exclude the PrintAdvancedDataGrid control from layout.
                printADG.includeInLayout = false;
                printADG.source = adg;

                // Add the print-specific control to the application.                
                addChild(printADG);
                
                // Start the print job.
                if (printJob.start() == false) {                
                    // User cancelled print job.
                    // Remove the print-specific control to free memory.                
                    removeChild(printADG);
                    return;
                }

                // Add the object to print. Do not scale it.
                printJob.addObject(printADG, FlexPrintJobScaleType.NONE);

                // Send the job to the printer.
                printJob.send();

                // Remove the print-specific control to free memory.                
                removeChild(printADG);
            }
        ]]>
    </mx:Script>

    <mx:VBox id="myVBox"
        width="100%" height="100%">
        <mx:AdvancedDataGrid id="adg"
            width="100%" height="100%">
            <mx:dataProvider>
                <mx:HierarchicalData source="{dpHierarchy}"/>
            </mx:dataProvider>
            <mx:columns>
                <mx:AdvancedDataGridColumn dataField="Region"/>
                <mx:AdvancedDataGridColumn dataField="Territory_Rep"
                    headerText="Territory Rep"/>
                <mx:AdvancedDataGridColumn dataField="Actual"/>
                <mx:AdvancedDataGridColumn dataField="Estimate"/>
            </mx:columns>
        </mx:AdvancedDataGrid>    

        <mx:Button id="myButton" 
            label="Print" 
            click="doPrint();"/>
    </mx:VBox>    
</mx:Application>

The executing SWF file for the previous example is shown below:

 

This example uses the PrintAdvancedDataGrid.source property to initialize the PrintAdvancedDataGrid control from the AdvancedDataGrid control.

To support the AdvancedDataGrid control, the PrintAdvancedDataGrid control adds the following properties not available in the PrintDataGrid control:

Property

Description

allowInteractions

If true, allow some interactions with the control, such as column resizing, column reordering, and expanding or collapsing nodes. The default value is false.

displayIcons

If true, display the folder and leaf icons in the navigation tree. The default value is true.

source

Initialize the PrintAdvancedDataGrid control and all of its properties from the specified AdvancedDataGrid control.

validPreviousPage

Indicates that the data provider contains data rows that precede the rows that the PrintAdvancedDataGrid control currently displays.

 



Posted by 1010
반응형

PrintDataGrid,percentHeight and multipage layouts

Categories: actionscript, flex
Written By: sebi

I rarely had to create any complex layouts for printing with Flex, until now.
The layout has to have different pages, with different elements on them. The issue is that the PrintDataGrid calculated it’s height right (well, almost) at the first page, but maintained this value to the rest of the pages – instead of recalculating based on that structures.

There is a chapter in the Flex help discussing this scenario: Using the PrintDataGrid control for multipage grids.

I implemented the whole print layout view based on this description, and quickly realized that even the result is not exactly what I wanted.

Print result

Print result

The help suggest something that sounds relevant to this issue, but it didn’t solve my problem.

When you use a PrintDataGrid control to print a single data grid across multiple pages, you queue each page of the grid individually. If your application customizes each page beyond simply using the nextPage() method to page through the PrintDataGrid, you must call the validateNow() method to update the page layout before you print each page, as shown in Print output component.

The root of the problem is that the PrintDataGrid’s setActualSize contains an interesting line, which resets the percentHeight of the grid to NaN. As a result, the parent container of the grid won’t resize the grid, even if it’s layout changes, and we call validateNow().

	/**
	 *  @private
	 *  setActualSize() is overridden to update _originalHeight.
	 */
	override public function setActualSize(w:Number, h:Number):void
	{
		if (!isNaN(percentHeight))
		{
			_originalHeight = h;
			super.percentHeight = NaN;
			measure();
			h = measuredHeight;
		}
 
		super.setActualSize(w, h);
 
		invalidateDisplayList();
 
		if (sizeToPage && !isNaN(explicitHeight))
			explicitHeight = NaN;
	}

The whole resizing cycle of the grid seemed to be quite complex, so I decided to look for an easier solution than trying to extend-override some of it’s steps, so ended up with the following:

	public function showPage( pageType:String ):void 
	{
		switch( pageType )
		{
			case "first":
			case "single":
				meetingInfoExtended.visible 		= true;
				meetingInfoExtended.includeInLayout	= true;
				meetingInfo.visible 		= false;
				meetingInfo.includeInLayout= false;						
				break;
			case "middle":
			case "last":
				meetingInfoExtended.visible 		= false;
				meetingInfoExtended.includeInLayout	= false;
				meetingInfo.visible 		= true;
				meetingInfo.includeInLayout= true;						
				break; 
		}
		printingGrid.percentHeight = 100;
		validateNow();
	}

Basically re-apply the percentHeight setting in every paging, forcing the grid to recalculate it’s size.

There was another small glitch, what caused a scrollbar to appear in the print layout – at least it tried to appear. I have a multi-line text there, an mx:Text, and I think the text couldn’t calculate it height fast enough, but if I didn’t pass a fixed height to it, the grid miss-calculated it’s height. But only the text caused this problem with the percent heights, other components could handle it.

One Response to “PrintDataGrid,percentHeight and multipage layouts”

  1. Robert Cesaric Says:

    Thanks for post.. We were just building a print view that head custom header/footer and had the same issue. Your percentHeight fix worked perfectly.

    We’re still noticing issues priting with the datagrid variableRowHeight but I’m much happier getting this bug fixed first. Thx!

 

Posted by 1010
반응형

How to Export into PDF/ / Flex + PDF / Generate PDF From Flex

To generate PDF files from Flex all you need is some external liberies like AlivePDF.swc or generatePdf.swc.
Im my Example i use Alive PDF as its Free and easy to use.
Get AlivePDF.swc
use following save structure to add images or Ui Container to add in PDF file
Get AlivePDF Here : AlivePDF
protected function savePDF():void
{
var myPDFEncoder:PDF = new PDF (Orientation.LANDSCAPE, Unit.MM);
myPDFEncoder.setDisplayMode(Display.FULL_PAGE);
myPDFEncoder.addPage();
myPDFEncoder.addImage(ChartDetails,null,0,0,myPDFEncoder.getMargins().width,myPDFEncoder.getMargins().height);

var bytes:ByteArray = myPDFEncoder.save(Method.LOCAL);
var fx:FileReference = new FileReference();
fx.save(bytes,"ABC.pdf");
}


Posted by 1010
반응형

Save file as PDF in flex

By in flex, Usability

Saving content as PDF from flex had always been a hassle, We know that doing such file operations in AIR is much simpler but due to the file saving ability added in Flash player 10 One can easily save files to the local system.

The next big question is how do i convert my content to PDF format so that it can be correctly saved into the file. Well for that folks at AlivePDF have done a gr8 job and now any one can encode their content into pdf and offer for download. They have a good documentation section which you can read and create more complex stuff.

For beginners i am writing a small example in which i will let the user download a PDF with embedded text or the Image depending on his choice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<mx:application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="522">
<mx:script>
    < ![CDATA[
    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
    import flash.text.*;
    import flash.utils.ByteArray;

    import mx.graphics.codec.JPEGEncoder;

    import org.alivepdf.layout.Orientation;
    import org.alivepdf.layout.Size;
    import org.alivepdf.layout.Unit;
    import org.alivepdf.pdf.PDF;
    import org.alivepdf.saving.Method;

    protected var fileRefPDF:PDF;

    private function onSaveClicked(e:Event):void
    {
    fileRefPDF = new PDF(Orientation.PORTRAIT, Unit.MM, Size.LETTER);
    fileRefPDF.addPage();

    if(check.selected){
    fileRefPDF.addImage(pics);
    fileRefPDF.addMultiCell(200,5,myname.text);
    }else{
    fileRefPDF.addMultiCell(200,5,myname.text);
    }

    var bytes:ByteArray = fileRefPDF.save(Method.LOCAL);
    var file:FileReference = new FileReference();
    file.save(bytes,"Untitled.pdf");
    }



    ]]>
</mx:script>

    <mx:canvas id="pics">
        <mx:image source="@Embed('hello.jpg')" x="198" y="19" width="311" height="208"/>
        <mx:label text="Oh!! Hi," x="330" y="166"/>
        <mx:label text="{myname.text}" x="330" y="184"/>
    </mx:canvas>



    <mx:label top="33" left="14" text="Save as PDF Test "  fontWeight="bold" fontSize="15"/>    
    <mx:button click="onSaveClicked(event)" label="Save to PDF" id="saveBtn" x="14" y="148"/>
    <mx:label text="Enter your name:" y="72" x="14"/>
    <mx:textinput id="myname"  x="14" y="90"/>
    <mx:checkbox id="check" label="Save image" selected="false"  x="14" y="121"/>
</mx:application>

the Screenshot of the same can be seen below.

Note: please include the AlivePDF swc in your project.

I have just skimmed the surface of the ocean with the above code. but you can write your own brew of concoction that could possibly bring WORLD PEACE :)

(-_-) happy loafing !

 

Posted by 1010
반응형

Toggling draggable columns in a Flex DataGrid control

By On August 30, 2007 · Leave a Comment

The following example demonstrates how you can enable/disable draggable columns in a Flex DataGrid control using the DataGrid class’s draggableColumns property, as well as toggling specific column’s dragability using the DataGridColumn class’s draggable property.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/30/toggling-draggable-columns-in-a-flex-datagrid-control/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Array id="arr">
        <mx:Object label="User 1" data="1" />
        <mx:Object label="User 2" data="2" />
        <mx:Object label="User 3" data="3" />
        <mx:Object label="User 4" data="4" />
        <mx:Object label="User 5" data="5" />
        <mx:Object label="User 6" data="6" />
        <mx:Object label="User 7" data="7" />
        <mx:Object label="User 8" data="8" />
    </mx:Array>

    <mx:ApplicationControlBar dock="true">
        <mx:CheckBox id="draggableColumnsCh"
                label="draggableColumns"
                selected="true" />

        <mx:CheckBox id="labelDraggableCh"
                label="label.draggable"
                selected="true" />

        <mx:CheckBox id="dataDraggableCh"
                label="data.draggable"
                selected="true" />
    </mx:ApplicationControlBar>

    <mx:DataGrid id="dataGrid"
            draggableColumns="{draggableColumnsCh.selected}"
            dataProvider="{arr}">
        <mx:columns>
            <mx:DataGridColumn dataField="label"
                    draggable="{labelDraggableCh.selected}" />
            <mx:DataGridColumn dataField="data"
                    draggable="{dataDraggableCh.selected}" />
        </mx:columns>
    </mx:DataGrid>

</mx:Application>

View source is enabled in the following example.

If you want to detect when a data grid column has been reordered, you can listen for the headerShift event on the DataGrid control, as seen in the following example:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/30/toggling-draggable-columns-in-a-flex-datagrid-control/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="horizontal"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.dataGridClasses.DataGridColumn;
            import mx.controls.DataGrid;
            import mx.events.IndexChangedEvent;

            private function dataGrid_headerShift(evt:IndexChangedEvent):void {
                var dg:DataGrid = DataGrid(evt.currentTarget);
                var column:DataGridColumn = dg.columns[evt.newIndex];
                debug.text += column.dataField + " (oldIndex:" + evt.oldIndex + ", newIndex:" + evt.newIndex + ")" + "\\n";
            }
        ]]>
    </mx:Script>

    <mx:Array id="arr">
        <mx:Object label="User 1" data="1" />
        <mx:Object label="User 2" data="2" />
        <mx:Object label="User 3" data="3" />
        <mx:Object label="User 4" data="4" />
        <mx:Object label="User 5" data="5" />
        <mx:Object label="User 6" data="6" />
        <mx:Object label="User 7" data="7" />
        <mx:Object label="User 8" data="8" />
    </mx:Array>

    <mx:DataGrid id="dataGrid"
            dataProvider="{arr}"
            headerShift="dataGrid_headerShift(event)">
        <mx:columns>
            <mx:DataGridColumn dataField="label" />
            <mx:DataGridColumn dataField="data" />
        </mx:columns>
    </mx:DataGrid>

    <mx:TextArea id="debug"
            width="{dataGrid.width}"
            height="{dataGrid.height}" />

</mx:Application>

View source is enabled in the following example.

 

Posted by 1010
반응형

Dragging rows between two different Flex DataGrid controls

By On September 19, 2007 · 42 Comments

The following example shows how you can use the dragEnabled, dropEnabled, and dragMoveEnabled properties with the Flex DataGrid control to copy and move rows between different data grids.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/19/dragging-rows-between-two-different-flex-datagrid-controls/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="horizontal"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Array id="arr">
        <mx:Object colA="Item A.0" colB="Item B.0" colC="Item C.0" />
        <mx:Object colA="Item A.1" colB="Item B.1" colC="Item C.1" />
        <mx:Object colA="Item A.2" colB="Item B.2" colC="Item C.2" />
        <mx:Object colA="Item A.3" colB="Item B.3" colC="Item C.3" />
        <mx:Object colA="Item A.4" colB="Item B.4" colC="Item C.4" />
        <mx:Object colA="Item A.5" colB="Item B.5" colC="Item C.5" />
        <mx:Object colA="Item A.6" colB="Item B.6" colC="Item C.6" />
        <mx:Object colA="Item A.7" colB="Item B.7" colC="Item C.7" />
        <mx:Object colA="Item A.8" colB="Item B.8" colC="Item C.8" />
        <mx:Object colA="Item A.9" colB="Item B.9" colC="Item C.9" />
    </mx:Array>

    <mx:ApplicationControlBar dock="true">
        <mx:Form>
            <mx:FormItem label="DataGrid #1:"
                    direction="horizontal">
                <mx:CheckBox id="dg1_dragEnabled"
                        label="dragEnabled" />
                <mx:CheckBox id="dg1_dropEnabled"
                        label="dropEnabled" />
                <mx:CheckBox id="dg1_dragMoveEnabled"
                        label="dragMoveEnabled" />
            </mx:FormItem>
            <mx:FormItem label="DataGrid #2:"
                    direction="horizontal">
                <mx:CheckBox id="dg2_dragEnabled"
                        label="dragEnabled" />
                <mx:CheckBox id="dg2_dropEnabled"
                        label="dropEnabled" />
                <mx:CheckBox id="dg2_dragMoveEnabled"
                        label="dragMoveEnabled" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>

    <mx:VBox width="50%">
        <mx:Label text="DataGrid #1" />
        <mx:DataGrid id="dataGrid1"
                width="100%"
                rowHeight="22"
                dataProvider="{arr}"
                dragEnabled="{dg1_dragEnabled.selected}"
                dragMoveEnabled="{dg1_dragMoveEnabled.selected}"
                dropEnabled="{dg1_dropEnabled.selected}"
                verticalScrollPolicy="on">
            <mx:columns>
                <mx:DataGridColumn dataField="colA"
                        headerText="Column A" />
                <mx:DataGridColumn dataField="colB"
                        headerText="Column B" />
                <mx:DataGridColumn dataField="colC"
                        headerText="Column C" />
            </mx:columns>
        </mx:DataGrid>
        <mx:Label text="{dataGrid1.dataProvider.length} items" />
    </mx:VBox>

    <mx:VBox width="50%">
        <mx:Label text="DataGrid #2" />
        <mx:DataGrid id="dataGrid2"
                width="100%"
                rowHeight="22"
                dataProvider="[]"
                dragEnabled="{dg2_dragEnabled.selected}"
                dragMoveEnabled="{dg2_dragMoveEnabled.selected}"
                dropEnabled="{dg2_dropEnabled.selected}"
                verticalScrollPolicy="on">
            <mx:columns>
                <mx:DataGridColumn dataField="colA"
                        headerText="Column A" />
                <mx:DataGridColumn dataField="colB"
                        headerText="Column B" />
                <mx:DataGridColumn dataField="colC"
                        headerText="Column C" />
            </mx:columns>
        </mx:DataGrid>
        <mx:Label text="{dataGrid2.dataProvider.length} items" />
    </mx:VBox>

</mx:Application>

View source is enabled in the following example.

Posted by 1010
반응형

출처 : http://wonsama.tistory.com/211

 

0. 참조 문서
blazeDS 개발자 가이드 : http://livedocs.adobe.com/blazeds/1/blazeds_devguide/

blazeDS 다운로드 : http://opensource.adobe.com/wiki/display/blazeds/download+blazeds+3



 

1. blazeds.war 파일 다운로드 이후 Eclipse or Tomcat Import



 

2. 중요 참조 [jre 5.0 이상에서만 동작함에 유의 !]



blazeds.war 파일을 초기 import 하면 WEB-INF 폴더가 생성됩니다.

WEB-INF
└flex
  └ services-config.xml : 전반적인 서비스 설정을 포함.
  └ messaging-config.xml : Message Push 서비스 등 메시지 관련 서비스 설정을 포함.
  └ remoting-config.xml : Remote Object 호출 서비스 설정을 포함.
  └ proxy-config.xml : 프록시 서비스를 사용할 때
└lib - Flex에서 사용되는 library 파일이 존재하는 폴더
└web.xml - Flex Session Management, MessageBroker Servlet 설정에 대한 내용 포함.

3. services-config.xml



: 기본 채널의 설정 및 포함하는 서비스 파일의 경로를 확인 할 수 있다.
my-amf, my-secure-amf, my-polling-amf ..

4. 나머지 .xml 파일



- 설정된 해당 서비스를 확인할 수 있다.
- destination id 설정을 통해 flex에서 접근할 수 있도록 설정한다.

ex)

ㄱ. MessagePush : 해당 채널에 대한 종착점 id를 설정한다.
< destination id="realMsg"/>

ㄴ. Remote Object : 해당 원격지 클래스를 호출하기 위한 종착점 id를 설정한다.
< destination id="fruitRO">
        <properties>
            <source>wonsama.test.FruitManager</source>
        </properties>
< /destination>

5. 기타 확인사항



ㄱ. <default-channels> 하위 노드에 여러개의 채널이 선언된 경우
맨 위쪽 부터 처리하며, 채널이 동작하지 않는 경우 다음 채널 서비스를 실행한다.

    <default-channels>
        <channel ref="my-streaming-amf"/> <!-- 처음 실행됨 -->
      <channel ref="my-polling-amf"/> <!-- 위 채널이 동작하지 않으면 동작 -->
    </default-channels>

ㄴ. StreamingAMFChannel 사용 시 <properties>의 하위노드가 1개 이상 존재해야 한다.
==> 존재하지 않으면 Explore에서 정상적으로 MessagePush가 동작하지 않음. (버그인듯?)

ex)
< channel-definition id="my-streaming-amf"
    class="mx.messaging.channels.StreamingAMFChannel">
    <endpoint
        url="http://{server.name}:{server.port}/{context.root}/messagebroker/streamingamf"
        class="flex.messaging.endpoints.StreamingAMFEndpoint" />
    <properties>
        <idle-timeout-minutes>0</idle-timeout-minutes>
        <max-streaming-clients>10</max-streaming-clients>
        <server-to-client-heartbeat-millis>5000    </server-to-client-heartbeat-millis>
        <user-agent-settings>
            <user-agent match-on="MSIE" kickstart-bytes="2048"
                        max-streaming-connections-per-session="3" />
            <user-agent match-on="Firefox" kickstart-bytes="2048"
                        max-streaming-connections-per-session="3" />
        </user-agent-settings>
    </properties>
< /channel-definition>

ㄷ. 익스플로러에서 모든 창을 종료하지 않으면 Messaging Service에서 Lock이 발생되어 실시간 메시지 수신을 할 수 없다(약 10초 ~ ???초). (MessageBroker쪽)

파폭에서는 발생하지 않지만 익스플로러에서는 위와 같은 문제가 발생하네여 아.... 초난감 ;;
24시간 시간 모니터링 툴을 제작시 반드시 고려를 하시기 바랍니다. 프로젝트 3개월 차에 이런 버그를 발견해 내서리 쩝...

고객사에는 뭐 끄지마세요 이런식으로 -_-; 아.... 중요 정보 인것 같아 이전 포스트에 덧칠하여 다시 올려 봅니다.

Posted by 1010
반응형

The DateFormatter class uses a format String to return a formatted date and time String from an input String or a Date object. The DateFormatter is a very simple formatter. To use it you just have to specify the formatString property, apply the format and you are done.
<mx:DateFormatter formatString="Y|M|D|A|E|H|J|K|L|N|S"/>
Here are some short explanations of what the characters in formatString represent:

Y – Year
M – month
D – Day
A – AM/PM indicator
E – day of the week
H – Hour (1-24 hours format)
J – Hour (0-23 hours format)
K – Hour in am/pm (0-11 hours format)
L – Hour in am/pm (1-12 hours format)
N – Minutes
S – Seconds
The formatString may also contain other words as separators between Y, M, D, A etc. as we will see in the example below.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical
   backgroundColor="white" 
    creationComplete="formatDates()" viewSourceURL="srcview/index.html">
    
    <mx:Script>
        <![CDATA[
            private function formatDates():void
            {
                dateFormatter.formatString = "DD/MM/YY";
                formattedDate1.text = dateFormatter.format(initialDate.text);
                dateFormatter.formatString = "EEE DD/MM/YY";
                formattedDate2.text = dateFormatter.format(initialDate.text);
                dateFormatter.formatString = "EEEE DD/MM/YY";
                formattedDate3.text = dateFormatter.format(initialDate.text);
                dateFormatter.formatString = "EEEE DD MMM YYYY";
                formattedDate4.text = dateFormatter.format(initialDate.text);
                dateFormatter.formatString = "EEEE DD MMMM YYYY";
                formattedDate5.text = dateFormatter.format(initialDate.text);
                dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN";
                formattedDate6.text = dateFormatter.format(initialDate.text);
                dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN A";
                formattedDate7.text = dateFormatter.format(initialDate.text);
                dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN.SS A";
                formattedDate8.text = dateFormatter.format(initialDate.text);
            }
        ]]>
    </mx:Script>
    
    <mx:DateFormatter id="dateFormatter" />
    <mx:Text text="Change The Initial Date And Format The New Dates
       fontWeight="bold"/>    
    <mx:Form>
        <mx:FormItem label="Initial Date:" >
            <mx:TextInput id="initialDate" text="01.01.2009 10:34 57" />
        </mx:FormItem>
        <mx:FormItem label="DD/MM/YY" >
            <mx:TextInput id="formattedDate1" />
        </mx:FormItem>
        <mx:FormItem label="EEE DD/MM/YY" >
            <mx:TextInput id="formattedDate2" />
        </mx:FormItem>
        <mx:FormItem label="EEEE DD/MM/YY" >
            <mx:TextInput id="formattedDate3" />
        </mx:FormItem>
        <mx:FormItem label="EEEE DD MMM YYYY" >
            <mx:TextInput id="formattedDate4" />
        </mx:FormItem>
        <mx:FormItem label="EEEE DD MMMM YYYY" >
            <mx:TextInput id="formattedDate5" />
        </mx:FormItem>
        <mx:FormItem label="EEEE DD MMMM YYYY at HH:NN" >
            <mx:TextInput id="formattedDate6" />
        </mx:FormItem>
        <mx:FormItem label="EEEE DD MMMM YYYY at HH:NN A" >
            <mx:TextInput id="formattedDate7" />
        </mx:FormItem>
        <mx:FormItem label="EEEE DD MMMM YYYY at HH:NN.SS A" >
            <mx:TextInput id="formattedDate8" />
        </mx:FormItem>
        <mx:FormItem >
            <mx:Button click="formatDates()" label="format dates"/>
        </mx:FormItem>
    </mx:Form></mx:Application>

 

Posted by 1010
반응형

Integrating Adobe Flex and IBM WebSphere Portal

Xiang Cheng (xcheng@cn.ibm.com), Software Engineer, IBM China
Zhi Hao Zhang (zhangzh@cn.ibm.com), Software Engineer, IBM China
Jia Gu (gujia@cn.ibm.com), Software Engineer, IBM China

Summary:  Adobe® Flex takes you to the next level of Web application development with the concept of Rich Internet Applications (RIAs), while IBM® WebSphere® Portal provides a composite tooling to build flexible, SOA-based solutions. But how do you get the two of them together? One option is to directly integrate Flex into WebSphere Portal server. This article walks you through a process to quickly build rich client and component-based Flex applications for WebSphere Portal, as well as a helpful method to reduce the size of WAR files.

Date:  12 May 2009
Level:  Introductory PDF:  A4 and Letter (520KB | 21 pages)Get Adobe® Reader®
Also available in:   Chinese

Activity:  19673 views
Comments:   3 (View | Add comment - Sign in)

Average rating 3 stars based on 12 votes Average rating (12 votes)
Rate this article

Prerequisites

This article is for Flex developers who want to integrate their applications with WebSphere Portal. It assumes that you are familiar with Flex at a basic programming level and that you are familiar with Java™ programming. It also assumes that you have administrative access to a working WebSphere Portal server for the relevant portions of the article. It does not, however, assume that you are familiar with programming or administering WebSphere Portal.

Along with this article, you will need the following tools installed to make sure the sample case works well.

  • Adobe Flex Builder — This article is written with Adobe Flex Builder 3. Of course, you can do it with the appropriate JDK and a text editor, but the amount of extra work is significant.
  • WebSphere Portal V6.0.1 or higher — If you are using WebSphere Portal V6.0, you should update your WebSphere Portal V6 environment. (See Resources.)
  • IBM Rational Software Architecture v7.0.0
  • IBM DB2 Enterprise v9.1

Overview of sample application

Let's briefly look at the business requirements of this sample application called TODOList. Many users want to keep records for their appointments, anniversaries, reminders, or any events. And they need to conveniently view their coming items, create new items, and delete any items if possible. Can we provide a smart tool to help them? In this article, we will show you how to build the application in a process that is similar to the way most developers create applications in order to illustrate the complete development procedures.

Figure 1 below shows the sample application infrastructure. We will quickly state the technical aspects of the sample before building the actual application with Adobe Flex and IBM WebSphere Portal. The whole application will be built in a WAR file, including presentation layer and business layer modules, although they are developed in the different projects.

The top rectangle represents a Flex project as the presentation layer that is built by MXML and ActionScript, while the bottom rectangle represents a Java project as the business layer that is built by Java and JDBC. The Flex application calls a Java service through a RemoteObject that is one of the remote procedure call (RPC) components provided by Flex. In this sample application, we will import BlazeDS to implement the remote object.


Figure 1. Infrastructure
A block diagram shows the relationships between the various components within WebSphere Portal.  The Presentation Layer is shown at the top with the Business Layer in the bottom, connected together through BlazeDS(remote object.)  MXML and AS are shown in the Presentation Layer.  Services and JDBC are shown in the Business layer.  A further connection goes to DB2 outside of the business layer from JDBC.

Build Flex project

Adobe Flex is a highly productive, free, open source framework for building and maintaining expressive Web applications that deploy consistently on all major browsers, desktops, and operating systems.

It consists of a rich component library with more than 100 proven, extensible UI components for creating RIAs. It also provides a standard-based language and programming model that supports common design patterns. MXML, a declarative XML-based language, is used to represent UI layout and behaviors, and each MXML file is a separate component. ActionScript, a powerful object-oriented programming language, is used to create client logic. ActionScript provides flow control and object manipulation features that are not available in MXML. Flex 3 was released at the end February 2008, and you can learn more about Flex 3 features from the Adobe Flex Web site. (See Resources.)

Flex applications can be built only by the free Flex SDK, which comprises the Flex framework (component class library) and Flex compiler, enabling you to freely develop and deploy Flex applications using an IDE of your choice. Developers can use Adobe Flex Builder 3 to dramatically accelerate development.

The Flex wizard guides you on how to quickly and easily create this sample in Flex Builder 3.

  1. Open Flex Builder 3, and select File --> New --> Flex Project.
  2. Enter TODOListFlex as the project name.
  3. Select the default location, which is the workspace, as the project location.
  4. Choose Web application as the application type.
  5. For the application server type, you may follow the steps in Adobe Flex 3 Help\Using Flex Builder 3\Flex Builder Basic\Working With Projects if you have a server. But in this sample, we select None, as the Figure 2 screen shot shows, because we don't need that.

Figure 2. New Flex project
A file tree shows the contents of TODOListFlex, including the folders bin-debug, html-template, libs and src.  Src is further expanded to show a folder image containing the file icon-delete.gif, a folder model containing the file TodoItemVBean.as, the folder util containing the file TokenResponder.as, and the file TODOListFlex.mxml.
  1. Keep all default settings for this Flex application and the build paths in the next two configuration pages.
  2. Click Finish to create this project.

Then, Flex Builder 3 will generate a primary MXML with the same name of new project. This application includes a MXML file, which starts with the <mx:Application> root tag, as follows in Listing 1.


Listing 1. MXML application root
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
</mx:Application>
            

In this section, you only need to care about the main file, TODOListFlex.mxml. You can use the Flex navigator view to import other resources (MXML, ActionScript, and Image) into the project from our sample code. A view of the project category is shown below in Figure 3.


Figure 3. Flex project category
A file tree shows the contents of TODOListFlex, including the folders bin-debug, html-template, libs and src.  Src is further expanded to show a folder image containing the file icon-delete.gif, a folder model containing the file TodoItemVBean.as, the folder util containing the file TokenResponder.as, and the file TODOListFlex.mxml.

The MXML editor in Flex Builder 3 allows you to work in either Source or Design mode at the top of the editor area. Make sure that you are in Source mode, and then add a <mx:Panel> component as the child of the main application to represent UI layout, and place a <mx:VBox> component in this panel to make it lay in vertical. See Listing 2.


Listing 2. Add panel and VBox in MXML file
<mx:Panel title="TODO List" width="100%" height="100%" 
   paddingLeft="4" paddingTop="8" paddingRight="8" paddingBottom="4">
   <mx:VBox width="100%">
   </mx:VBox>
</mx:Panel>

Put a <mx:DataGrid> component between <mx:VBox> tags to list all to-do items. We define an ArrayCollection todoItemColl and assign it as the dataProvider for the DataGrid. (See Listing 3.) We will call RemoteObject service to obtain data for this ArrayCollection in the section, "Use RemoteObject in Flex."


Listing 3. Add DataGrid in VBox
<mx:DataGrid id="todoListDG" dataProvider="{todoItemColl}">
   <mx:columns>
   <mx:DataGridColumn visible="false" dataField="id"/>
   <mx:DataGridColumn width="100" headerText="Date" dataField="deadlineStr"/>
   <mx:DataGridColumn width="400" headerText="Subject" dataField="task"/>
   ...
   </mx:columns>
</mx:DataGrid>

There is a form under the VBox to allow users to add new to-do items. The form contains three text fields (such as Date, Subject, and Owner) and a button. We use a <mx:Grid> component here to control the UI alignment. (See Listing 4.)


Listing 4. Add grid for item form
<mx:Grid>
   <mx:GridRow>
      <mx:GridItem> 
         <mx:Label text="Date:"/>
      </mx:GridItem>
      <mx:GridItem>
         <mx:DateField id="deadlineDateField" formatString="YYYY-MM-DD"/>
      </mx:GridItem>
   </mx:GridRow>
   ...
   <mx:GridRow>
      <mx:GridItem colSpan="2" horizontalAlign="right">
         <mx:Button label="Add" click="saveNewItem()"/>
      </mx:GridItem>
   </mx:GridRow>
</mx:Grid>

Then we create client logic with ActionScript codes within a <mx:Script> tag and wrap the contents in a CDATA construct. (See Listing 5.) To access the different data sources, we define a constant, USE_MOCK_DATA, to control whether the application accesses remote data or local mock data. Now we set the constant value to be true because we are just showing it as a separate application for now. We will elaborate on how to use RemoteObject Service to assess data in the section, "Use RemoteObject in Flex."


Listing 5. Add script to call data source
<mx:Script>
   <![CDATA[
      …
      private static const USE_MOCK_DATA:Boolean = true;	…
      private function getTodoList():void
      {
         if(USE_MOCK_DATA) {
            // Creat the mock data
         }
         else {
            // Use remote object to access the back-service
         }
      }
      …
   ]]>
</mx:Script>

You will find more sample code in the attachment. (See Downloads.) After the above steps, select TODOListFlex.mxml and click the Run button at the toolbar. Flex Builder will compile this application and show the below pages, as in Figure 4.


Figure 4. TODOList Page
A screen shot of the TODOList Page showing a title, TODO List at the top.  Below that is a label which reads Total 3 TODO item(s).  Beneath the label is a table with four columns labeled from left to right Date, Subject, Owner.  The fourth columns is unlabeled.  Next follow three sample Todos with a date in column 1, a description in column 2, a person's name in column 3 and a checked box in the fourth column.  Under the table are entry fields for Date, Subject and Owner with an Add button.

Build portal project

WebSphere Portal is a framework that lets you plug in new features or extensions called portlets. Portlets are applications within WebSphere Portal, which are the encapsulation of reusable components that combine Web-based content, application functionality, and access to resources.

WebSphere Portal, starting with Version 5.0.2.1, provides a runtime environment for both JSR 168 Portlet API and IBM Portlet API. JSR 168 is a specification from the Java Community Process for the standardization of portlets. The specification was developed to provide interoperability for running portlets on any vendor's implementation of the JSR 168 portlet container. The IBM Portlet API is now deprecated in WebSphere Portal V6.0 in order to show IBM's commitment to the JSR 168 standard portlet API. Also, many new functions will only be available to standard portlets. We will use the JSR 168 standard portlet in our sample.

This section shows how to create a new portlet project using the Rational Software Architecture (RSA) wizard. (See Figure 5.)

  1. Open RSA, and select File --> New --> Project.
  2. Select Portlet Project to create a project.
  3. Enter TODOList as the project name.
  4. Target runtime should be WebSphere Portal V6.0 stub.
  5. Portlet API should be JSR 168 Portlet.
  6. Select the checkbox of "Create a portlet".
  7. Make sure the Basic Portlet is selected as Portlet type.
  8. Click Next, leaving all fields as default.
  9. Click Finish to create the portlet project.

Figure 5. New portlet project
New Portlet Project window with the following settings: Project name is "TODOList;" Project contents has "use default" checked; Target Runtime is "WebSphere Portal v6.0 stub;" EAR Membership has "Add project to an EAR" checked and EAR Project Name set to "TODOListEAR;" Portlet API is "JSR 168 Portlet;" Create a portlet is checked; Portlet name is "TODOList;" Portlet type is "Basic Portlet;" Show advanced settings is checked.

After you finish the above steps, the project category should look like Figure 6.


Figure 6. Portlet project category
The file structure of the New Portlet Project is shown with a root of TODOList with the skeletal structure and components created.

Actually, you can deploy this portlet on your portal server now. But we will integrate the Flex application created in the previous section into the portlet project first.


Integrate Flex into the portlet project

To integrate the Flex application into our portlet project we must complete a few steps.

Introducing Web-tier compiler

The Flex compiler creates SWF files that run in Adobe Flash Player. Flex offers several kinds of compilers: the Web-tier compiler, the mxmlc command-line compiler, and the Flex Builder project compiler. In this article, we will use the Web-tier compiler, which is a set of servlets and servlet filters that run in a J2EE application server. The application server passes on requests from *.mxml files to the servlet container, which then compiles into a SWF file and returns the results to the client. In this case, it allows you to simply copy the Flex files into a directory visible to your server, and the flex codes will be compiled automatically when you request the main application file using your Web browser. This also allows you to rapidly compile, test, and deploy an application instead of compiling your MXML files into a SWF file and then deploying its wrapper files on a Web server.

You should download the FlexModule_J2ER from the Adobe open source Web site if you have not already. Do the following steps to introduce it into this sample portlet project.

  1. Unzip the webtier.war file to a directory called webtier.
  2. Copy flex-bootstrap.jar and flex-bootstrap-jsp.jar from the webtier\WEB-INF\lib to the corresponding WEB-INF\lib directory of the portlet project.
  3. Copy all files and directories from the webtier\WEB-INF\flex directory to the corresponding WEB-INF\flex directory of the portlet project.
  4. Update web.xml file content in the WEB-INF\ directory of the portlet project according to the web.xml file in the webtier\WEB-INF (You can copy the web.xml from the sample code which we have updated accordingly -- see Downloads).

Introducing BlazeDS

The Flex SDK contains features for accessing server-side data. These components use RPC to interact with server environments to provide data to Flex applications and send data to back-end data sources.

Three kinds of RPC components are supported by Flex: HTTPService, WebService, and RemoteObject. A client-side RPC component calls a remote service and then stores the response data in an ActionScript object where you can easily obtain the data.

RemoteObject

We use the RemoteObject component in this sample because it lets you access business logic directly in its native format rather than formatting it as XML, as you do with HTTPService or WebService. This saves you the time required to expose existing logic as XML. The Flex application can access a Java object directly by remote invocation of a method on a designated object. Those objects on the server can then deal with its native data types as arguments, query a database from those arguments, and return its native data types as values.

Another benefit of RemoteObject services is the speed of communication across the wire. Data exchanges still happen over HTTP or HTTPS, but the data itself is serialized into the Action Message Format (AMF), which is a binary format for data serialization/deserialization and remote method invocation. It improves performance by dramatically compressing the size of data transferred and parsing binary data into objects in memory far more efficiently than parsing XML data.

Using BlazeDS

BlazeDS is an Adobe open source project that employs RemoteObject component to access remote Java objects. It contains configurable channels that transport the data between the client and server and can run on a J2EE application server.

You can download the BladeDS package from the Adobe open source Web site. (See Resources.) Do the following steps to enable this portlet application to use BlazeDS:

  1. Unzip the blazeds.war to a directory called blazeds.
  2. Copy all jar files from blazeds\WEB-INF\lib to the WEB-INF\lib directory.
  3. Copy all configuration files from the blazeds\WEB-INF\flex directory to the WEB-INF\flex directory of this application. Overwrite if there are existing ones.
  4. Define MessageBrokerServlet and a session listener in WEB-INF\web.xml of this portlet application, as below in Listing 6. You can skip this step if you copied the web.xml from our sample code.

Listing 6. Define MessageBrokerSerlet and session listener
<!-- Http Flex Session attribute and binding listener support -->
<listener>
   <listener-class>flex.messaging.HttpFlexSession</listener-class>
</listener>
	
<!-- MessageBroker Servlet -->
<servlet>
   <servlet-name>MessageBrokerServlet</servlet-name>
   <display-name>MessageBrokerServlet</display-name>
   <servlet-class> flex.messaging.MessageBrokerServlet </servlet-class>

   <init-param>
      <param-name>services.configuration.file</param-name>
      <param-value>/WEB-INF/flex/services-config.xml</param-value>
   </init-param>

   <load-on-startup>1</load-on-startup>
</servlet>
         

Copy Flex code into the portlet project

Copy all files under the src directory from the Flex project to the directory, WebContent/_TODOList/jsp/html. The category of the portlet project should look like Figure 7.


Figure 7. Copy Flex code into portlet
The file structure of the TODOList project is shown.  Under the WebContent, _TODOList, jsp, html section are the files TODOListFlex.mxml and TODOListPortletView.jsp.

Create Java RemoteObject class

For simplicity, we need only one Java RemoteObject class, TodoItemRO, as the remote business service. You can copy the Java source code and the jdbc.properties file from the sample code (WEB-INF\src) to the portlet project. TodoItem is the only entity Java bean in this sample. (See Figure 8.)


Figure 8. Java RemoteObject class
Diagram shows two boxes side by side.  On the left is the Java Class TodoItemBO with the contained components.  On the right is the Java Class containing TodoItem with its components.  A connecter labeled "use" runs TodoItemBO to TodoItem.

Configure RemoteObject in portal

Flex finds the remote services according to its configuration file, services-config.xml, in the WEB-INF\flex. You need to specify the fully qualified class name in the source property of a remoting service destination in the BlazeDS services-config.xml file, or a file that it includes by reference, such as the remoting-config.xml file. The class also must have a no-arg constructor which will be used by Flex to instantiate an instance. We configured the single Java RemoteObject in the remoting-config.xml file which is in WEB-INF\flex, as below in Listing 7.


Listing 7. Configure RemoteObject in portal
<destination id= ‘todoItemRO’>
   <properties>			 
      <source> todolist.ro.TodoItemRO </source>
   </properties>
</destination> 
            

Use RemoteObject in Flex

Now that we have created and configured the remote object, it's time to use it as a remote service.

First, create a RemoteObject component in TODOListFlex.mxml with a unique ID, srvTODOList. The value of the destination should match the destination entry in the WEB-INF\flex\remoting-config.xml file in the portal project. In this sample, it is todoItemRO. (See Listing 8.)


Listing 8. Create RemoteObject component in Flex
<mx:RemoteObject id="srvTODOList" destination="todoItemRO" showBusyCursor="true" 
requestTimeout="10"/>
           

Next, create an AsyncToken object to call the Java method defined in the destination service using the unique ID of the RemoteObject component. The AsyncToken class provides a place to set additional or token-level data for asynchronous RPC operations.

It also allows an IResponder to be attached for an individual call (or, callback method). We define a simple responder class, TokenResponder, that implements the IResponder Interface (see the code sample, TODOListFlex\src\util\TokenResponder.as). It will call the specified callback method when Java returns or raises a specified alert as the handler of any fault. We add it as the responder of the AsyncToken object, get the response data, and transform it into a Flex variable type. (See Listing 9.)


Listing 9. Create callback method in Flex
var asyncToken:AsyncToken = AsyncToken(srvTODOList.getTodoItems());
asyncToken.addResponder(new TokenResponder(displayTodoItems, "Error Getting TODO List"));

private function displayTodoItems(event:ResultEvent):void
{
   todoItemColl = event.result as ArrayCollection;
   todoItemColl.refresh();
}
           

Include Flex component in JSP

The Flex compiler module for J2EE application servers also provides a JSP tag library that lets you include Flex applications in JSPs. Add the following tag library declaration to your JSP page to import Flex 3 Tag Library in JSP: WebContent\_TODOList\jsp\html\TODOListPortletView.jsp. (See Listing 10.)


Listing 10. Include Flex tag library in JSP
<%@ taglib uri="FlexTagLib" prefix="mm" %>

You can either refer a separate MXML file or include MXML syntax directly in the JSP by the <mm:mxml> tag. (See Listing 11.)


Listing 11. Include Flex project in JSP
<mm:mxml source="TODOListFlex.mxml" width="100%" height="768">
</mm:mxml>

You can delete all old content of the JSP which is generated by RSA. You can refer to the JSP in the sample code.


Deployment

Make use of the J2EE Web application archive feature in RSA to export a WAR file so that you can install on a staging or production portal server.

Make sure that the constant USE_MOCK_DATA in the WebContent\_TODOList\jsp\html\TODOListFlex.mxml file has been set to false in order to use RemoteObject to get TODO list. Copy the DB2 JDBC driver jars from sample code to the WEB-INF\lib.

Do the following steps to export the WAR file from this sample project.

  1. Right-click this sample project name and select Export from the pop-up menu.
  2. Select WAR file in the Export window, and then select Next.
  3. Specify a location for the new WAR file.
  4. Click Finish and make sure you can find the WAR file under the location.

Log on to WebSphere Portal Server with the administrator role, and go to the Administrative page to install the WAR file by following these steps.

  1. If it's not already running, start the portal server. From the control panel select Portlet Management , Web Modules.
  2. On the "Manage Web Modules" page, click Install.
  3. On the "Installing a Web module" page, use the Browse button to locate the WAR file. Click Next and Finish. This step may take several minutes due to the large size. You can reduce the size of the WAR using shared lib. (Refer to the section, "Reduce WAR size".)

After installing the portlet, we need to place it into a page. From the Administrative page of the portal server do the following steps.

  1. Navigate to Portal --> User Interface --> Manage Pages.
  2. Locate the page to add a portlet and click Edit Page Layout.
  3. Add the portlet (TODOList) in the page, and click Done to save the changes.

Now go the page and verify the TODOList portlet.


Figure 9. TODOList Portlet
A screen shot shows the TODOList screen from before.  The title is TODOList.  Beneath the title is a label reading "Total 1 TODO item(s).  Then follows a table with 4 columns, labeled from left to right: Date, Subject and Owner.  The 4th column has no label.  One entry is shown in the table, with the Date as "2008-10-06," the Subject as "Submit the paper," and the Owner as "Sean."  The 4th column contains a box which is checked.  Below the table are data entry fields containing the same information listed in the table with an Add button.

If you host your portal server on a Linux® system (skip this section if you are using a Windows® system), the flash may not be displayed. You may need to configure the java.awt.headless parameter for JVM of portal server as value of true. Follow these steps to do so:

  1. Start the WebSphere Application Server: /opt/IBM/WebSphere/AppServer/bin/startServer.sh server1
  2. Open the WebSphere Application Server Administrative Console: http://server:10001/ibm/console
  3. Navigate to Server --> Application Server --> WebSphere_Portal --> Process Definition --> Java Virtual --> Custom Properties

Figure 10. Configure the java.awt.headless
A screen shot shows the administrative tool for Websphere on the screen Application servers, WebSphere Portal, Process Definition, Java Virtual Machine, Custom Properties.  The value java.awt.headless has been set to "true."
  1. Restart the WebSphere Application Server and Portal Server.

Reduce WAR size (shared lib)

This step is optional. Because the size of the WAR may be larger than 20MB, you can move some of the contents into the WebSphere Application Service shared lib in order to reduce the size. Refer to the section, "Create a shared library", in the developerWorks article, "Using resource environment providers in WebSphere Application Server". (See Resources.)


Summary

This article covered the major features and enhancements during the integration development between Adobe Flex and WebSphere Portal. We also examined the runtime environment used to show the sample application and how easy it can be to create an RIA application and integrate Portal features before delivering the applications for an improved user experience.



Download

Description Name Size Download method
Sample code TODOList.war 23MB HTTP

Information about download methods


Resources

Learn

Get products and technologies

Posted by 1010
반응형
 

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute">
 <mx:Script>
       
  import mx.controls.Menu;
  import mx.events.MenuEvent;
  private var myMenu:Menu;
  private function createAndShow():void {
   ta1.text="";
   myMenu = Menu.createMenu(null, myMenuData, false);
   myMenu.labelField="@label";
   myMenu.addEventListener(MenuEvent.ITEM_ROLL_OVER,menuShowInfo);
   myMenu.show(225, 10);
  }
  private function menuShowInfo(event:MenuEvent):void {
   ta1.text="event.type: " + event.type;
   ta1.text+="\nevent.label: " + event.label;
   ta1.text+="\nevent.index: " + event.index;
   if (event.item) {
    ta1.text+="\nItem label: " + event.item.@label
    ta1.text+="\nItem selected: " + event.item.@toggled;
    ta1.text+= "\nItem type: " + event.item.@type;
   }
  }
  
  [Bindable]
  public var menuData:Array = [
   {label: "MenuItem A", children: [
    {label: "SubMenuItem A-1", enabled: false},
    {label: "SubMenuItem A-2", type: "normal"}]},
   {label: "MenuItem B", type: "check", toggled: true},
   {label: "MenuItem C", type: "check", toggled: false},
   {type: "separator"},
   {label: "MenuItem D", children: [
    {label: "SubMenuItem D-1", type: "radio", groupName: "g1"},
    {label: "SubMenuItem D-2", type: "radio", groupName: "g1",toggled: true},
    {label: "SubMenuItem D-3", type: "radio", groupName: "g1"}]}
  ];
  
 </mx:Script>
 <mx:XML id="myMenuData">
  <xmlRoot>
   <menuitem label="MenuItem A">
    <menuitem label="SubMenuItem A-1" enabled="false" />
    <menuitem label="SubMenuItem A-2" />
   </menuitem>
   <menuitem label="MenuItem B" type="check" toggled="true" />
   <menuitem label="MenuItem C" type="check" toggled="false" />
   <menuitem type="separator" />
   <menuitem label="MenuItem D">
    <menuitem label="SubMenuItem D-1" type="radio" groupName="one" />
    <menuitem label="SubMenuItem D-2" type="radio" groupName="one" toggled="true" />
    <menuitem label="SubMenuItem D-3" type="radio" groupName="one" />
   </menuitem>
  </xmlRoot>
 </mx:XML>
 <mx:Button x="10" y="5" label="Open XML Popup" click="createAndShow();" />
 <mx:TextArea x="10" y="70" width="200" height="300" id="ta1" />
</mx:Application>

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 28. 14:57
반응형

Setting the vertical gap between items in a Flex VBox container

By On January 3, 2008 · 7 Comments

The following example shows how you can control the amount of vertical spacing between items in a VBox container by setting the verticalGap style.

Full code after the jump.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/01/03/setting-the-vertical-gap-between-items-in-a-flex-vbox-container/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">
 
    <mx:Style>
        HSlider {
            dataTipPlacement: bottom;
            dataTipPrecision: 0;
        }
    </mx:Style>
 
    <mx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import mx.events.SliderEvent;
 
            private function slider_change(evt:SliderEvent):void {
                vBox.setStyle("verticalGap", evt.value);
            }
 
            private function vBox_creationComplete(evt:FlexEvent):void {
                slider.value = vBox.getStyle("verticalGap");
            }
        ]]>
    </mx:Script>
 
    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain">
            <mx:FormItem label="verticalGap:"
                    direction="horizontal">
                <mx:HSlider id="slider"
                        minimum="0"
                        maximum="20"
                        liveDragging="true"
                        snapInterval="1"
                        tickInterval="1"
                        change="slider_change(event);" />
                <mx:Label text="{slider.value}" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>
 
    <mx:VBox id="vBox"
            width="100%"
            creationComplete="vBox_creationComplete(event);">
        <mx:Box width="100%" height="50" backgroundColor="red" />
        <mx:Box width="100%" height="50" backgroundColor="haloOrange" />
        <mx:Box width="100%" height="50" backgroundColor="yellow" />
        <mx:Box width="100%" height="50" backgroundColor="haloGreen" />
        <mx:Box width="100%" height="50" backgroundColor="haloBlue" />
    </mx:VBox>
 
</mx:Application>

View source is enabled in the following example.

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 28. 13:37
반응형

Using embedded fonts

Rather than rely on a client machine to have the fonts you specify, you can embed TrueType font (TTF) or OpenType font (OTF) families in your Flex application. This means that the font is always available to Flash Player when the application is running, and you do not have to consider the implications of a missing font.

Embedded fonts have the following benefits:

  • Client environment does not need the font to be installed.
  • Embedded fonts are anti-aliased, which means that their edges are smoothed for easier readability. This is especially apparent when the text size is large.
  • Embedded fonts can be partially or fully transparent.
  • Embedded fonts can be rotated.
  • Embedded fonts provide smoother playback when zooming.
  • Text appears exactly as you expect when you use embedded fonts.
  • When you embed a font, you can use the advanced anti-aliasing information that provides clear, high-quality text rendering in SWF files. Using advanced anti-aliasing greatly improves the readability of text, particularly when it is rendered at smaller font sizes. For more information about advanced anti-aliasing, see Using advanced anti-aliasing.

Using embedded fonts is not always the best solution, however. Embedded fonts have the following limitations and drawbacks:

  • Embed only TrueType or OpenType fonts. To embed other font types such as Type 1 PostScript fonts, embed that font in a SWF file that you create in Flash 8, and then embed that SWF file in your Flex application. For more information, see Embedding fonts from SWF files.
  • Embedded fonts increase the file size of your application, because the document must contain font outlines for the text. This can result in longer download times for your users.
  • Embedded fonts, in general, decrease the legibility of the text at sizes smaller than 10 points. All embedded fonts use anti-aliasing to render the font information on the client screen. As a result, fonts may look fuzzy or illegible at small sizes. To avoid this fuzziness, you can use advanced anti-aliasing to render fonts in Flex applications. For more information, see Using advanced anti-aliasing.
  • In some cases, embedded fonts can be truncated when they are used in visual components. In these cases, you might be required to change the padding properties of the component by using style properties or subclassing it. This only occurs with some fonts.

You typically use Cascading Style Sheets (CSS) syntax for embedding fonts in Flex applications. You use the @font-face "at-rule" declaration to specify the source of the embedded font and then define the name of the font by using the fontFamily property. You must specify the @font-face declaration for each face of the font for the same family that you use. The source can be a local Java Runtime Environment (JRE) font or one that is accessible by using a file path. You use this font family name in your MXML code to refer to the embedded font.

Note: Check your font licenses before embedding any font files in your Flex applications. Fonts might have licensing restrictions that preclude them from being stored as vector information.

If you attempt to embed a font that the Flex compiler cannot find, Flex throws an error and your application does not compile.

Embedded font syntax

To embed TrueType or OpenType fonts, you use the following syntax in your style sheet or <mx:Style> tag:

@font-face {
    src: url("location") | local("name");
    fontFamily: alias;
    [fontStyle: normal | italic | oblique;]
    [fontWeight: normal | bold | heavy;]
    [advancedAntiAliasing: true | false;]
}

The src property specifies how the compiler should look for the font and the name of the font to look for. You can load a font either by its filename (by using src:url) or by its system font name (by using src:local). This property is required. For more information, see Locating embedded fonts. The src property also helps determine which font manager the compiler will use; for more information, see About the font managers.

The fontFamily property sets the alias for the font that you use to apply the font in style sheets. This property is required. If you embed a font with a family name that matches the family name of a system font, the Flex compiler gives you a warning. You can disable this warning by setting the show-shadows-system-font-warnings compiler option to false.

The fontStyle and fontWeight properties set the type face values for the font. These properties are optional. The default values are normal.

The advancedAntiAliasing property determines whether to include the advanced anti-aliasing information when embedding the font. This property is optional. The default value is true. You cannot use this option when embedding fonts from a SWF file (see Embedding fonts from SWF files). For more information on using advanced anti-aliasing, see Using advanced anti-aliasing.

The following example embeds the MyriadWebPro.ttf font file:

@font-face {
    src: url("../assets/MyriadWebPro.ttf");
    fontFamily: myFontFamily;
    advancedAntiAliasing: true;
}

The following example embeds that same font, but by using its system font name:

@font-face {
    src: local("Myriad Web Pro");
    fontFamily: myFontFamily;
    advancedAntiAliasing: true;
}

After you embed a font with an @font-face declaration, you can use the value of the fontFamily property, or alias, in a type or class selector. The following example uses myFontFamily, the value of the fontFamily property, as the font in the VBox type selector:

<?xml version="1.0"?>
<!-- fonts/EmbeddedFontFace.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Style>
     @font-face {
        src:url("../assets/MyriadWebPro.ttf");
        fontFamily: myFontFamily;
        advancedAntiAliasing: true;
     }
     
     VBox {
        fontFamily: myFontFamily;
        fontSize: 15;
     }     

     Panel {
        paddingLeft: 10;
        paddingTop: 10;
        paddingBottom: 10;
        paddingRight: 10;
     }
  </mx:Style>

  <mx:Panel title="Embedded Font Applied With Type Selector">

     <mx:VBox>
        <!-- This button attempts to use the font of the VBox container. -->
        <mx:Button label="Click Me"/>
        <mx:Label text="This is a label."/> 
        <mx:TextArea width="250">
            <mx:text>
                The text in this TextArea control uses the 
                myClass class selector.
            </mx:text>
        </mx:TextArea>
     </mx:VBox>
  </mx:Panel>

  <!-- This button uses the default font because it is not in
   the VBox. -->
  <mx:Button label="Click Me"/>
    
</mx:Application>

The executing SWF file for the previous example is shown below:

You can also apply the embedded font inline by specifying the alias as the value of the control's fontFamily property, as the following example shows:

<?xml version="1.0"?>
<!-- fonts/EmbeddedFontFaceInline.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Style>
     @font-face {
        src:url("../assets/MyriadWebPro.ttf");
        fontFamily: myFontFamily;
        advancedAntiAliasing: true;
     }

     Panel {
        paddingLeft: 10;
        paddingTop: 10;
        paddingBottom: 10;
        paddingRight: 10;
     }
  </mx:Style>

  <mx:Panel title="Embedded Font Applied Inline">
     <mx:VBox fontFamily="myFontFamily">
        <mx:Button label="Click Me"/>
        <mx:Label text="This is a label."/> 
        <mx:TextArea width="200">
            <mx:text>
                The text in the TextArea control is Myriad Web Pro.
            </mx:text>
        </mx:TextArea>
     </mx:VBox>
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below:

When you run this example, you might notice that the Button control's label uses a system font. This is because the default style of a Button control's label uses a bold typeface. However, the embedded font's typeface (Myriad Web Pro) does not contain a definition for the bold typeface. To have the Button control's label use the proper typeface, you must either embed a font's bold typeface so that the label of a Button control is rendered with the correct font, or change the Button control's typeface to be non-bold. For information on embedding bold typefaces, see Using multiple typefaces.

Locating embedded fonts

The src property in the @font-face declaration specifies the location of the font family. You can specify a url or a local function. The following table describes these functions:

Attribute

Description

url

Embeds a TrueType or OpenType font by location by specifying a valid URI to the font. The URI can be relative (for example, ../fontfolder/akbar.ttf) or absolute (for example, c:/myfonts/akbar.ttf).

local

Embeds a locally accessible TrueType or OpenType font by name rather than location. You use the font name, and not the filename, for the font. For example, you specify "Akbar Bold Italic" rather than "AkbarBI.ttf".

You can embed fonts that are locally accessible by the application server's Java Runtime Environment (JRE). These fonts include the *.ttf files in the jre/lib/fonts folder, fonts that are mapped in the jre/lib/font.properties file, and fonts that are made available to the JRE by the operating system (OS).

On Windows, TTF files in the /windows/fonts directory (or /winnt/fonts) are available to the local function. On Solaris or Linux, fonts that are registered with a font server, such as xfs, are available.

The font name that you specify is determined by the operating system. In general, you do not include the font file's extension, but this is OS-dependent. For more information, consult your operating system documentation.

You must specify the url or local function of the src property in the @font-face declaration. All other properties are optional. In general, you should use url rather than local, because pointing to a file is more reliable than using a reference controlled by the operating system.

Do not mix embedded and nonembedded fonts in the same fontFamily property.

Embedding fonts in ActionScript

You can embed TrueType or OTF font files or system fonts by location or by name by using the [Embed] metadata tag in ActionScript. To embed a font by location, you use the source property in the [Embed] metadata tag. To embed a font by name, you use the systemFont property in the [Embed] metadata tag.

The following examples embed fonts by location by using the [Embed] tag syntax:

<?xml version="1.0"?>
<!-- fonts/EmbeddedFontFaceActionScriptByLocation.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Style>
     .mystyle1 {
        fontFamily:myMyriadFont;
        fontSize: 32pt;
     }
     .mystyle2 {
        fontFamily:myBoldMyriadFont;
        fontSize: 32pt;
        fontWeight: bold;
     }
  </mx:Style>
  
  <mx:Script>
     /* 
      * Embed a font by location. 
      */
     [Embed(source='../assets/MyriadWebPro.ttf', 
        fontName='myMyriadFont', 
        mimeType='application/x-font'
     )] 
     // You do not use this variable directly. It exists so that 
     // the compiler will link in the font.
     private var font1:Class;
     
     /* 
      * Embed a font with bold typeface by location. 
      */
     [Embed(source='../assets/MyriadWebPro-Bold.ttf', 
        fontWeight='bold', 
        fontName='myBoldMyriadFont', 
        mimeType='application/x-font', 
        advancedAntiAliasing='true'
     )] 
     private var font2:Class;
     
  </mx:Script>

  <mx:Panel title="Embedded Fonts Using ActionScript">
     <mx:VBox>
        <mx:Label 
            width="100%" 
            height="75" 
            styleName="mystyle1" 
            text="This text uses the MyriadWebPro font." 
            rotation="15"
        />
        <mx:Label 
            width="100%" 
            height="75" 
            styleName="mystyle2" 
            text="This text uses the MyriadWebPro-Bold font." 
            rotation="15"
        />
     </mx:VBox>
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below:

You use the value of the fontName property that you set in the [Embed] tag as the alias (fontFamily) in your style definition.

To embed a font with a different typeface (such as bold or italic), you specify the fontWeight or fontStyle properties in the [Embed] statement and in the style definition. For more information on embedding different typefaces, see Using multiple typefaces.

To show you that the example runs correctly, the Label controls are rotated. If the fonts were not correctly embedded, the text in the Label controls would disappear when you rotated the text.

To embed local or system fonts, you use the system font name rather than the filename for the font. You also specify that name using the systemFont property in the [Embed] tag rather than the source attribute. Otherwise, you use the same syntax, as the following example shows:

<?xml version="1.0"?>
<!-- fonts/EmbeddedFontFaceActionScriptByName.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Style>
     .mystyle1 {
        fontFamily:myPlainFont;
        fontSize: 32pt;
     }
     .mystyle2 {
        fontFamily:myItalicFont;
        fontSize: 32pt;
        fontStyle: italic;
     }
  </mx:Style>
  
  <mx:Script>
     /* 
      * Embed a font by name. 
      */
     [Embed(systemFont='Myriad Web Pro', 
        fontName='myPlainFont', 
        mimeType='application/x-font'
     )] 
     // You do not use this variable directly. It exists so that 
     // the compiler will link in the font.
     private var font1:Class;
     
     /* 
      * Embed a font with italic typeface by name. 
      */
     [Embed(systemFont='Myriad Web Pro', 
        fontStyle='italic', 
        fontName='myItalicFont', 
        mimeType='application/x-font', 
        advancedAntiAliasing='true'
     )] 
     private var font2:Class;
     
  </mx:Script>

  <mx:Panel title="Embedded Fonts Using ActionScript">
     <mx:VBox>
        <mx:Label 
            width="100%" 
            height="75" 
            styleName="mystyle1" 
            text="This text uses the plain typeface." 
            rotation="15"
        />
        <mx:Label 
            width="100%" 
            height="75" 
            styleName="mystyle2" 
            text="This text uses the italic typeface." 
            rotation="15"
        />
     </mx:VBox>
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below:

To get the system font name in Windows, install the Font properties extension. Then right-click the font's file in Windows Explorer and select the Names tab. Use the value under Font Family Name as the systemFont value.

You can specify a subset of the font's character range by specifying the unicodeRange parameter in the [Embed] metadata tag or the @font-face declaration. Embedding a range of characters rather than using the default of all characters can reduce the size of the embedded font and, therefore, reduce the final output size of your SWF file. For more information, see Setting character ranges.

Using advanced anti-aliasing

When you embed fonts, you can use advanced anti-aliasing to provide those fonts with additional information about the font. Embedded fonts that use the advanced anti-aliasing information are typically clearer and appear sharper at smaller font sizes.

By default, fonts that you embed in Flex applications use the advanced anti-aliasing information. This default is set by the fonts.advanced-anti-aliasing compiler option in the flex-config.xml file (the default value is true). You can override this default value by setting the value in your style sheets or changing it in the configuration file. To disable advanced anti-aliasing in style sheets, you set the advancedAntiAliasing style property to false in your @font-face rule, as the following example shows:

@font-face {
    src:url("../assets/MyriadWebPro.ttf");
    fontFamily: myFontFamily;
    advancedAntiAliasing: false;
}

Using advanced anti-aliasing can degrade the performance of your compiler. This is not a run-time concern, but can be noticeable if you compile your applications frequently or use the web-tier compiler. Using advanced anti-aliasing can also cause a slight delay when you load SWF files. You notice this delay especially if you are using several different character sets, so be aware of the number of fonts that you use. The presence of advanced anti-aliasing information may also cause an increase in the memory usage in Flash Player and Adobe® AIR™. Using four or five fonts, for example, can increase memory usage by approximately 4 MB.

When you embed fonts that use advanced anti-aliasing in your Flex applications, the fonts function exactly as other embedded fonts. They are anti-aliased, you can rotate them, and you can make them partially or wholly transparent.

Font definitions that use advanced anti-aliasing support several additional styles properties: fontAntiAliasType, fontGridFitType, fontSharpness, and fontThickness. These properties are all inheriting styles.

Because the advanced anti-aliasing-related style properties are CSS styles, you can use them in the same way that you use standard style properties, such as fontFamily and fontSize. For example, a text-based component could use subpixel-fitted advanced anti-aliasing of New Century 14 at sharpness 50 and thickness -35, while all Button controls could use pixel-fitted advanced anti-aliasing of Tahoma 10 at sharpness 0 and thickness 0. These styles apply to all the text in a TextField control; you cannot apply them to some characters and not others.

The default values for the advanced anti-aliasing styles properties are defined in the defaults.css file. If you replace this file or use another style sheet that overrides these properties, Flash Player and AIR use the standard font renderer to render the fonts that use advanced anti-aliasing. If you embed fonts that use advanced anti-aliasing, you must set the fontAntiAliasType property to advanced, or you lose the benefits of the advanced anti-aliasing information.

The following table describes these properties:

Style property

Description

fontAntiAliasType

Sets the antiAliasType property of internal TextField controls. The valid values are normal and advanced. The default value is advanced, which enables advanced anti-aliasing for the font.

Set this property to normal to prevent the compiler from using advanced anti-aliasing.

This style has no effect for system fonts or fonts embedded without the advanced anti-aliasing information.

fontGridFitType

Sets the gridFitType property of internal TextField controls. The valid values are none, pixel, and subpixel. The default value is pixel. For more information, see the TextField and GridFitType classes in the Adobe Flex Language Reference.

This property has the same effect as the gridFitType style property of the TextField control for system fonts, only it applies when you embed fonts with advanced anti-aliasing.

Changing the value of this property has no effect unless the fontAntiAliasType property is set to advanced.

fontSharpness

Sets the sharpness property of internal TextField controls. The valid values are numbers from -400 to 400. The default value is 0.

This property has the same effect as the fontSharpness style property on the TextField control for system fonts, only it applies when you embed fonts with advanced anti-aliasing.

Changing the value of this property has no effect unless the fontAntiAliasType property is set to advanced.

fontThickness

Sets the thickness property of internal TextField controls. The valid values are numbers from -200 to 200. The default value is 0.

This property has the same effect as the fontThickness style property on the TextField control for system fonts, only it applies when you embed fonts with advanced anti-aliasing.

Changing the value of this property has no effect unless the fontAntiAliasType property is set to advanced.

Detecting embedded fonts

You can use the SystemManager class's isFontFaceEmbedded() method to determine whether the font is embedded or whether it has been registered globally with the register() method of the Font class. The isFontFaceEmbedded() method takes a single argument--the object that describes the font's TextFormat--and returns a Boolean value that indicates whether the font family you specify is embedded, as the following example shows:

<?xml version="1.0"?>
<!-- fonts/DetectingEmbeddedFonts.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
     creationComplete="determineIfFontFaceIsEmbedded()">
  <mx:Style>
     @font-face {
        src: url(../assets/MyriadWebPro.ttf);
        fontFamily: myPlainFont;
        advancedAntiAliasing: true;
     }
     
     .myStyle1 {
        fontFamily: myPlainFont; 
        fontSize:12pt
     }
  </mx:Style>
  <mx:Script><![CDATA[
     import mx.managers.SystemManager;
     import flash.text.TextFormat;
     
     public function determineIfFontFaceIsEmbedded():void {
        var tf1:TextFormat = new TextFormat();
        tf1.font = "myPlainFont";
        
        var tf2:TextFormat = new TextFormat();
        tf2.font = "Arial";
        
        var b1:Boolean = Application.application.systemManager.
           isFontFaceEmbedded(tf1);
        var b2:Boolean = Application.application.systemManager.
           isFontFaceEmbedded(tf2);
        l1.text = tf1.font + " (" + b1 + ")";
        l2.text = tf2.font + " (" + b2 + ")";
     }
  ]]></mx:Script>
  <mx:Text id="text1" styleName="myStyle1" text="Rotate Me"/>

  <mx:HBox>
    <mx:Button label="Rotate +1" click="++text1.rotation;"/>
    <mx:Button label="Rotate -1" click="--text1.rotation;"/>
  </mx:HBox>

  <mx:Form>
     <mx:FormItem label="isFontFaceEmbedded:">
        <mx:Label id="l1"/>
     </mx:FormItem>         
     <mx:FormItem label="isFontFaceEmbedded:">
        <mx:Label id="l2"/>
     </mx:FormItem>         
  </mx:Form>    
</mx:Application>

The executing SWF file for the previous example is shown below:

You can use the Font class's enumerateFonts() method to output information about device or embedded fonts. The following example lists embedded fonts:

<?xml version="1.0"?>
<!-- fonts/EnumerateFonts.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="listFonts()">
  <mx:Style>
     @font-face {
        src:url("../assets/MyriadWebPro.ttf");
        fontFamily: myFont;
        advancedAntiAliasing: true;
     }

     @font-face {
        src:url("../assets/MyriadWebPro-Bold.ttf");
        fontFamily: myFont;
        fontWeight: bold;
        advancedAntiAliasing: true;
     }

     @font-face {
        src:url("../assets/MyriadWebPro-Italic.ttf");
        fontFamily: myFont;
        fontStyle: italic;
        advancedAntiAliasing: true;
     }
     
     .myPlainStyle {
        fontSize: 20;
        fontFamily: myFont;
     }
     
     .myBoldStyle {
        fontSize: 20;
        fontFamily: myFont;
        fontWeight: bold;
     }

     .myItalicStyle {
        fontSize: 20;
        fontFamily: myFont;
        fontStyle: italic;
     }
  </mx:Style>

  <mx:Script><![CDATA[
     private function listFonts():void {
        var fontArray:Array = Font.enumerateFonts(false);
        for(var i:int = 0; i < fontArray.length; i++) {
           var thisFont:Font = fontArray[i];
           if (thisFont.fontType == "embedded") {
              ta1.text += "FONT " + i + ":: name: " + thisFont.fontName + "; typeface: " + 
                thisFont.fontStyle + "; type: " + thisFont.fontType + "\n";
           }
        }
     }
  ]]></mx:Script>

  <mx:HBox borderStyle="solid"> 
     <mx:Label text="Plain Label" styleName="myPlainStyle"/> 
     <mx:Label text="Bold Label" styleName="myBoldStyle"/> 
     <mx:Label text="Italic Label" styleName="myItalicStyle"/> 
  </mx:HBox>

  <mx:TextArea id="ta1" height="200" width="400"/>

</mx:Application>

The executing SWF file for the previous example is shown below:

The following list shows the output.

name: myFont; typeface: regular; type: embedded
name: myFont; typeface: bold; type: embedded
name: myFont; typeface: italic; type: embedded

The enumerateFonts() method takes a single Boolean argument: enumerateDeviceFonts. The default value of the enumerateDeviceFonts property is false, which means it returns an Array of embedded fonts by default.

If you set the enumerateDeviceFonts argument to true, the enumerateFonts() method returns an array of available device fonts on the client system, but only if the client's mms.cfg file sets the DisableDeviceFontEnumeration property to 0, the default value. If you set the DisableDeviceFontEnumeration property to 1, Flash Player cannot list device fonts on a client computer unless you explicitly configure the client to allow it. For more information about configuring the client with the mms.cfg file, see the Flash Player documentation.

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 28. 13:18
반응형
2009.1.21 : 데이타가 너무 촘촘하게 붙는 경우 직선과 차이가 없어지는 문제로, 수정하였습니다.

This is a DashLine Line Segment Renderer for Flex Chart. (Tested in FLEX 3.0)
You must modify the package & class path.


Click this icon to download the source.
모자이크 부분은 고객사 로고 때문임..;; (Don't care the mossaic)

LineSeries 에서 점선을 사용해야 해서 만들게 된 Dash Line Renderer이다.
해당 클래스만 넣었으므로 Class Path는 적절히 고쳐서 사용할 것.


사용법은 LineChart 등에 쓰이는 LineSeries에 lineSegmentRenderer 값으로 해당 Class Path를 쓰면 된다.
예를 들어

component.LineRenderer.DotLine01 로 넣었다면

<mx:LineSeries lineSegmentRenderer="component.LineRenderer.DotLine01" ..... />
이렇게 넣으면 된다.


다운 받은 걸 열어보면 DotLineBase.as 와 DotLine01.as 가 있는데 DotLine01.as 를 복제해 가며 점선의 종류를 늘려 가면 된다.

개별 Class에서 설정 가능한 옵션은

gap=6; // 점선 사이 간격
length=6; // 점선 길이
lineWeight=3; // 선 굵기
lineAlpha=1; // 선 알파


이다.

선 색은 기본적으로 시리즈에 정의된 선 색을 쓰게 된다.

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 28. 11:23
반응형
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
   
<mx:DateFormatter id="df" formatString="JJ:NN:SS" />
   
<mx:Script>
        <![CDATA[
            private const minimum:Date = new Date( "Apr 1 2011 01:03:54 AM");
            private const maximum:Date = new Date( "Apr 1 2011 03:07:54 AM");
            private function labelFunction(item:Object,
                                           field:String,
                                           index:Number):String {
                return df.format(item as Date);
            }
        ]]>
   
</mx:Script>

   
<mx:CartesianChart width="600" height="200">

       
<mx:horizontalAxis>
           
<mx:DateTimeAxis
               
minimum = "{minimum}"
               
maximum = "{maximum}"
               
displayLocalTime="true"
               
labelFunction="labelFunction"
               
labelUnits="minutes"
           
/>
           
<!--
                interval="15"
            -->

       
</mx:horizontalAxis>

   
</mx:CartesianChart>

</mx:Application>

Gives this flex screenshot

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 28. 11:01
반응형

The DateFormatter is a very simple formatter. To use it you just have to specify the formatString property, apply the format and you are done.

<mx:DateFormatter formatString="Y|M|D|A|E|H|J|K|L|N|S"/>

Here are some short explanations of what the characters in formatString represent:

Y – Year
M – month
D – Day
A – AM/PM indicator
E – day of the week
H – Hour (1-24 hours format)
J – Hour (0-23 hours format)

K – Hour in am/pm (0-11 hours format)
L – Hour in am/pm (1-12 hours format)
N – Minutes
S – Seconds

The formatString may also contain other words as separators between Y, M, D, A etc. as we will see in the example below.

Here is an example that uses the Flex DateFormatter Class

<?xml version="1.0" encoding="utf-8"?>
<!--http://www.popamihai.com/2009/07/flex/example-of-using-the-dateformatter-class-in-flex/-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundColor="white" 
	creationComplete="formatDates()" viewSourceURL="srcview/index.html">
 
	<mx:Script>
		<![CDATA[
			private function formatDates():void{
				dateFormatter.formatString = "DD/MM/YY";
				formattedDate1.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEE DD/MM/YY";
				formattedDate2.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD/MM/YY";
				formattedDate3.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMM YYYY";
				formattedDate4.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMMM YYYY";
				formattedDate5.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN";
				formattedDate6.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN A";
				formattedDate7.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN.SS A";
				formattedDate8.text = dateFormatter.format(initialDate.text);
			}
		]]>
	</mx:Script>
 
	<mx:DateFormatter id="dateFormatter" />
 
	<mx:Text text="Change The Initial Date And Format The New Dates" fontWeight="bold"/>
 
	<mx:Form>
		<mx:FormItem label="Initial Date:" >
			<mx:TextInput id="initialDate" text="01.01.2009 10:34 57" />
		</mx:FormItem>
		<mx:FormItem label="DD/MM/YY" >
			<mx:TextInput id="formattedDate1" />
		</mx:FormItem>
		<mx:FormItem label="EEE DD/MM/YY" >
			<mx:TextInput id="formattedDate2" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD/MM/YY" >
			<mx:TextInput id="formattedDate3" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMM YYYY" >
			<mx:TextInput id="formattedDate4" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMMM YYYY" >
			<mx:TextInput id="formattedDate5" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMMM YYYY at HH:NN" >
			<mx:TextInput id="formattedDate6" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMMM YYYY at HH:NN A" >
			<mx:TextInput id="formattedDate7" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMMM YYYY at HH:NN.SS A" >
			<mx:TextInput id="formattedDate8" />
		</mx:FormItem>
		<mx:FormItem >
			<mx:Button click="formatDates()" label="format dates"/>
		</mx:FormItem>
	</mx:Form>
</mx:Application>

In the following example the formatString is displayed on the left column, and the formatted dates are displayed in the TextInput controls from the right column. To see how the different formats work change the “Initial Date” with a valid date and press the “format dates” button.

View Source is enabled in the above example. To view the source files right click on the swf and choose “View Source” from the context menu.

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 22. 09:33
반응형
Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 20. 14:12
반응형

출처 : http://flexponential.com/2009/09/23/deleting-items-in-a-list-from-an-item-renderer/

 

It’s easy to delete an item in a spark List from within an item renderer. This is handy if you have a List with a custom renderer that provides a button to delete the item that is associated with that renderer.

You can do this by using the ItemRenderer’s owner property to access the List it is in, drill down to its dataProvider and delete the data item:

<s:ItemRenderer>
    <fx:Script>
        <![CDATA[
                import spark.components.List;
                public function deleteItem():void {
                    var parentList:List = owner as List;
                    // remove the item
                    parentList.dataProvider.removeItemAt(parentList.dataProvider.getItemIndex(data))
                }
            ]]>
        </fx:Script>
        <s:HGroup>
            <s:Label text="{data}" />
            <s:Button id="remove" label="X"  click="deleteItem()"/>
        </s:HGroup>
</s:ItemRenderer>

Another approach is to delete items based on the selectedItem/selectedIndex, but I prefer this method since it allows you to delete items without needing to select them.

Here is an example that uses the deleteItem() method listed above:

View Source

This should work the same way for DataGroup and SkinnableDataContainer as well.

Note: This sample requires Flex SDK 4.0.0.10545 or higher. You can get the latest SDK builds from opensource.adobe.com.

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 20. 13:52
반응형

<init시 itemrenderer를 갖고 있는 start_addr_deny(datagrid)에 접근할 addEventListener추가>

private function init():void{
start_addr_deny.addEventListener("status_bt", status_btHandler);

}

<dispatchEvent를 이용한 클릭시 외부 접근>

<mx:DataGridColumn id="check_Add" width="50">
<mx:itemRenderer>
<mx:Component>
<mx:HBox horizontalAlign="center">
<mx:CheckBox click="dispatchEvent(new Event('status_bt', true))"/>
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 13. 19:20
반응형

Taking screenshots in Flex 3 using the ImageSnapshot.captureBitmapData() method

By On November 17, 2007 · 11 Comments

As we saw in a previous entry, “Taking screenshots in Flex 3 using the ImageSnapshot.captureImage() method”, it is possible to take a screenshot of an item on the display list using the static ImageCapture.captureImage() method. Once the image is captured, we accessed the image’s pixel data using the ImageCapture object’s data property, which was displayed using the SWFLoader control.

The ability to load a ByteArray object directly into a SWFLoader was added in Flex 3 build 187814, you may need to update your SDK build by downloading a recent nightly build from http://labs.adobe.com/technologies/flex/sdk/flex3sdk.html.

The following example shows how you can take a snapshot of an item on the display list using the static ImageSnapshot.captureBitmapData() method, which returns a BitmapData object, as seen in the following snippet:

var imageBitmapData:BitmapData = ImageSnapshot.captureBitmapData(source);
swfLoader.source = new Bitmap(imageBitmapData);

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/11/17/taking-screenshots-in-flex-3-using-the-imagesnapshotcapturebitmapdata-method/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.graphics.ImageSnapshot;

            private function takeSnapshot(source:IBitmapDrawable):void {
                var imageBitmapData:BitmapData = ImageSnapshot.captureBitmapData(source);
                swfLoader.source = new Bitmap(imageBitmapData);
            }
        ]]>
    </mx:Script>

    <mx:Array id="arr">
        <mx:Object col1="Row 1, Col 1" col2="Row 1, Col 2" />
        <mx:Object col1="Row 2, Col 1" col2="Row 2, Col 2" />
        <mx:Object col1="Row 3, Col 1" col2="Row 3, Col 2" />
        <mx:Object col1="Row 4, Col 1" col2="Row 4, Col 2" />
        <mx:Object col1="Row 5, Col 1" col2="Row 5, Col 2" />
        <mx:Object col1="Row 6, Col 1" col2="Row 6, Col 2" />
    </mx:Array>

    <mx:ApplicationControlBar dock="true">
        <mx:Button label="Take snapshot of DataGrid"
                click="takeSnapshot(dataGrid);" />
    </mx:ApplicationControlBar>

    <mx:HBox>
        <mx:DataGrid id="dataGrid" dataProvider="{arr}" />
        <mx:SWFLoader id="swfLoader">
            <mx:filters>
                <mx:DropShadowFilter />
            </mx:filters>
        </mx:SWFLoader>
    </mx:HBox>

</mx:Application>

View source is enabled in the following example.

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 13. 13:23
반응형

출처 : http://blog.marines.co.kr/archives/58

FLEX에서 SWFLoader를 이용하여 플래시SWF파일을 Embed시킬 경우에
간단하게 변수를 전달하는 것이 안되더군요. (SWFLoader.params = 어쩌고 이런 방식이 안됨;;)

이를 위해서는 이전부터 존재했던 LocalConnection을 사용하여야 통신이 가능합니다.

Javascript, AJAX를 사용하여도 되지만, 독립적인 실행이 가능하게 하려는 취지에는 맞지않지요.

private var lc:LocalConnection;

private function init():void {
lc = new LocalConnection();
lc.addEventListener(StatusEvent.STATUS, onStatus);
}

public function clickHandler():void {
webservice.getPhotoListArray.send();
}

private function onStatus(e:StatusEvent):void {
switch(e.level) {
case “status”:
trace(“swf send success”);
break;
case “error”:
trace(“Failed”);
break;
}
}

public function resultHandler(event:ResultEvent):void{
datas = ArrayCollection(event.result);
sendPhotoListData(datas, _imagePath);
}
private function onStatus(e:StatusEvent):void {
switch(e.level) {
case “status”:
trace(“swf send success”);
break;
case “error”:
trace(“Failed”);
break;
}
}
private function sendPhotoListData(data:*, _imagePath:String):void { //PhotoListData Request
try {
lc.send(“photoListData”, “dataHandler”, data, _imagePath);
}catch (e:Error) {
Alert.show(String(e));
}
}
public function faultHandler(event:FaultEvent):void {
Alert.show(event.fault.faultDetail, “Error”);
}



이와 같은 방법으로 FLEX의 송신부에서 localConnection 객체를 생성해주고 StatusEvent리스너를 달아줍니다.

FLASH의 수신부에는 아래의 코드를 입력해줍니다.

public function UIMFL_Base() {
Security.allowDomain(“*”);
//
lc = new LocalConnection();
lc.client = this;
try {
lc.connect(“photoListData”);
} catch (error:ArgumentError) {
trace(“Can’t connect…the connection name is already being used by another SWF”);
}
thumblist.mask = thumbMask;
}// End of Function

//Flex to Flash Data Response Handler Define
public function dataHandler(dt:*, _path:String):void {
var responseData:* = dt;
_strDomain = _path;
totalElementNum = responseData.length;
}


수신부에서는 이처럼 세팅합니다. 이런 방식으로 FLEX에서 플래시로 데이터를 전달할수 있고, 플래시에서 다시 FLEX로 데이터를 전달할때는 이 방식도 가능하겠지만, Event를 디스패치 시켜서 받는 방식도 가능합니다


private function init():void{
swfObj.content.addEventListener(“SWF_EVENT”, swfHandler);
}
private function swfHandler(e:Event):void {
currentOsgsSeq = e.target.currentTargetID;
}

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 10. 16:17
반응형

 

// 검색일자 초기화
    var now:Date = new Date();
    fromYYYYMMDD.selectedDate = now;      // 검색 : 시작일
    toYYYYMMDD.selectedDate = DateUtil.addDays(now,1); // 검색  : 종료일

----------------- dateutil.as

package biz.sehwa.core.utils
{
 public class DateUtil
 {
  public function DateUtil()
  {
  }
  
  /**
   * Add Month
   *
   * @param date:Date
   * @param months:Number Month Count
   * @return Date
   */
  public static function addMonths(date:Date, months:Number):Date{
   var rtnDate:Date = new Date(date.getFullYear(), date.getMonth() + months, date.getDate());
   return rtnDate;
  }
  
  /**
   * Add Week
   *
   * @param date:Date
   * @param weeks:Number Week Count
   * @return Date
   */
  public static function addWeeks(date:Date, weeks:Number):Date {
   return addDays(date, weeks*7);
  }
  
  /**
   * Add Date
   *
   * @param date:Date
   * @param days:Number Date Count
   * @return Date
   */
  public static function addDays(date:Date, days:Number):Date {
   return addHours(date, days*24);
  }
  
  /**
   * Add Hours
   *
   * @param date:Date
   * @param hrs:Number Hour Count
   * @return Date
   */
  public static function addHours(date:Date, hrs:Number):Date {
   return addMinutes(date, hrs*60);
  }
  
  /**
   * Add Minutes
   *
   * @param date:Date
   * @param mins:Number Minute Count
   * @return Date
   */
  public static function addMinutes(date:Date, mins:Number):Date {
   return addSeconds(date, mins*60);
  }
  
  /**
   * Add Seconds
   *
   * @param date:Date
   * @param secs:Number Seconds Count
   * @return Date
   */
  public static function addSeconds(date:Date, secs:Number):Date {
   var mSecs:Number = secs * 1000;
   var sum:Number = mSecs + date.getTime();
   return new Date(sum);
  }
 }
}

Posted by 1010
반응형

Flex 4 animate properties

by on Jan.25, 2010, under Actual RIA info, Adobe AIR, Adobe Flex

I came across a situation while doing a Flex 4 upgrade for an Adobe Developer Center sample app where I wanted to use some the Spark animate properties classes.

This is SO cool because it gives you truly granular control over every aspect of a component you want to animate. In the sample I’m upgrading, there is an extended TileGroup component that has three columns and two rows of charts for an enterprise dashboard application. When a user clicks a button to zoom in on any given chart, I wanted to make use of some of the new Spark effects to really create a 3D look and feel quickly (without delving too much into custom layouts). Actually, the layout I made is a custom TileGroup, but I wanted to point out some ways you can use the Animate class to make sweet transitions on any property of a component in your own apps for simple animation, without having to create custom layouts.

This super simple test was to find out if I could use the Animate class to move the entire TileGroup to a new X,Y and increase its horizontalGap and verticalGap at the same time. In other words, could I use the Animate class to create my whole animation in one shot, truly custom? I watched Chet Haase on Adobe TV’s Codedependent on animating properties, and it worked great, but I needed it running in ActionScript.

The above code is the MXML that worked great for my test, and here’s the AS3 equivalent:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import spark.effects.Scale;
import spark.effects.Move;
import mx.effects.Parallel;
import spark.effects.Animate;
import spark.effects.animation.MotionPath;
import spark.effects.animation.SimpleMotionPath;
import flash.events.MouseEvent;
public function handleClick(event:MouseEvent):void
{
var p:Parallel = new Parallel(t);
p.duration = 1000;
var s:SimpleMotionPath = new SimpleMotionPath();
s.valueFrom = t.horizontalGap;
s.valueTo = 200;
s.property = "horizontalGap";
var s2:SimpleMotionPath = new SimpleMotionPath();
s2.valueFrom = t.verticalGap;
s2.valueTo = 200;
s2.property = "verticalGap";
var v:Vector. = new Vector.();
v.push( s );
v.push( s2 );
var a:Animate = new Animate();
a.motionPaths = v;
var m:Move = new Move();
m.xTo = t.width/2;
m.yTo = t.height/2;
p.addChild( a );
p.addChild( m );
p.play();
}

Thanks to Chet too for spotting what my tired eyes didn’t see :P sheesh, it’s been one of those days.

This sample is not very exciting, except for the fact that it gives you the idea how you can animate any property over time. If I wanted to (and I have for my project) animate the x, y, z, width, and height at the same time using the Animate class, you could easily create a very specific animation this way.

For my purposes, I used the SimpleMotionPath to specify certain properties to change, and since the Animate class’s Interpolator is set to NumberInterpolator by default, it worked out great to fill in the steps for the “tween” automatically for me. I’d like to get to the point where I come up with my own Flat-terpolator for some other project one day just to see what I can create, but for now, this worked out fine.

You can download the FXP for this sample and try it out yourself here. Once you see how this works, you can imagine the possibilities afforded to Flex 4 that will allow you to make some truly amazing animations. Mine’s turning out to be pretty cool, but you’ll have to wait until the ADC releases it :P In the meantime, you can get started on this one to catch up on Flex 4 and Flash Builder.

Posted by 1010
00.Flex,Flash,ActionScript2013. 4. 25. 15:54
반응형

<?xml version="1.0" encoding="utf-8"?>
<s:MXAdvancedDataGridItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
          xmlns:s="library://ns.adobe.com/flex/spark"
          xmlns:mx="library://ns.adobe.com/flex/mx"
          focusEnabled="true"
          autoDrawBackground="false"> <-- 마우스 오버시 백그라운드 
 <fx:Script>
  <![CDATA[
   import mx.controls.AdvancedDataGrid;
   import mx.controls.advancedDataGridClasses.AdvancedDataGridListData;
   
   private const NORMALCY_COLOR:uint = 0x000000; // 0:정상(검정)
   private const PROBLEM_COLOR:uint = 0xFF0000; // 1:장치이상(빨강)
   private const INSPECTION_COLOR:uint = 0xFFFF00; // 2:점검(노랑)
   private const WARNING_COLOR:uint = 0xFF9900; // 3:경고(주황)
   private const DANGER_COLOR:uint = 0xFF0000; // 4:위험(빨강)
   
   private var strData:String;
   private var strDataError:String;
   
   override public function set data(value:Object) : void {
//    super.data = value;
    var arryStr:Array;
    if(value != null){
     
     var tmpStr:String  = (value[AdvancedDataGridListData(listData).dataField]) as String;
     arryStr = tmpStr.split("/");
     if(arryStr.length > 1){

      itemLabel.text = arryStr[0] as String;
      itemLabel.setStyle("color",getTLDS_TC_Color(arryStr[1]));
      
      strData = arryStr[0] as String;
      strDataError= arryStr[1] as String;
      itemLabel.addEventListener(MouseEvent.ROLL_OVER,overToolTip);
     }
    }
   }
   
   private function overToolTip(event:Event):void{
    this.toolTip = "[측정값:"+this.strData+"] [상태:"+getTLDS_TC_ErrorMsg(strDataError)+"]";
   }
   
   
   private function getTLDS_TC_Color(val:String):* {
    var rt:uint = 0x000000;
 
    //0:정상, 1:장치이상, 2:점검, 3:경고, 4:위험
    switch(val) {
     case "0": rt = 0x000000; break; //정상 검정  0x000000
     case "1": rt = 0xFF0000; break; //에러 빨강
     case "2": rt = 0xFFFF00; break; //주의 노랑
     case "3": rt = 0xFF9900; break; //경고 주황
     case "4": rt = 0xFF0000; break; //에러 빨강
    }
    return rt;
   }
   
   private function getTLDS_TC_ErrorMsg(val:String):String {
    var rtnStr:String = "";
    
    //0:정상, 1:장치이상, 2:점검, 3:경고, 4:위험
    switch(val) {
     case "0": rtnStr = "정상"; break; //정상 검정  0x000000
     case "1": rtnStr = "에러"; break; //에러 빨강
     case "2": rtnStr = "주의"; break; //주의 노랑
     case "3": rtnStr = "경고"; break; //경고 주황
     case "4": rtnStr = "에러"; break; //에러 빨강
    }
    return rtnStr;
   }
  ]]>
 </fx:Script>
 
 <s:Label id="itemLabel" text="" left="2" right="2" verticalCenter="0" backgroundAlpha="0"/> <-- 여기도...(랜더러로 만들지 않고 그냥 컴포넌트로 만들면 이부분만 처리해주면됨... 랜더러로 만드려면 위에 부분에 처리해줘야 함..

1시간 삽질후~~


</s:MXAdvancedDataGridItemRenderer>

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 4. 24. 19:29
반응형

출처 : http://eflex.tistory.com/entry/DataGrid-%EC%A0%84%EC%B2%B4-%EB%8B%A4%EC%8B%9C-%EA%B7%B8%EB%A6%AC%EC%A7%80-%EC%95%8A%EA%B3%A0-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%A7%8C-%EA%B0%B1%EC%8B%A0%ED%95%98%EA%B8%B0

 

<?xml version="1.0" encoding="utf-8"?>
< s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="application1_creationCompleteHandler(event)" >


<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.events.FlexEvent;

[Bindable]
private var ac:ArrayCollection = new ArrayCollection();
private var arr:Array = new Array();

protected function application1_creationCompleteHandler(event:FlexEvent):void
{

arr.push({first:"aaaaa", second:"bbbbbb"});
arr.push({first:"ccccc", second:"dddddd"});
arr.push({first:"eeeee", second:"ffffff"});
arr.push({first:"ggggg", second:"iiiiii"});
arr.push({first:"aaaaa", second:"bbbbbb"});
arr.push({first:"ccccc", second:"dddddd"});
arr.push({first:"eeeee", second:"ffffff"});
arr.push({first:"ggggg", second:"iiiiii"});

ac.source = arr;
dg.dataProvider = ac;
}


protected function button1_clickHandler(event:MouseEvent):void
{
//var arr2:Array = new Array();
arr[0]={first:"2222", second:"bbbbbb"};
arr[1]={first:"333", second:"dddddd"};
arr[2]={first:"444", second:"ffffff"};
arr[3]={first:"5555", second:"iiiiii"};

ac.refresh();
//또는 dg.dataProvider.dispatchEvent(new CollectionEvent(CollectionEvent.COLLECTION_CHANGE));
}

]]>
</fx:Script>

<mx:DataGrid id="dg" >
<mx:columns>
<mx:DataGridColumn dataField="first" />
<mx:DataGridColumn dataField="second"/>
</mx:columns>
</mx:DataGrid>

<mx:Button id="addBtn" y="200" label="add" click="button1_clickHandler(event)"/>
< /s:Application>

Posted by 1010