반응형

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
반응형

 

swfobject_2_2.zip

 

What is SWFObject?

SWFObject 2:

  • Offers two optimized Flash Player embed methods; a markup based approach and a method that relies on JavaScript
  • Offers a JavaScript API that aims to provide a complete tool set for embedding SWF files and retrieving Flash Player related information
  • Utilizes only one small JavaScript file (10Kb / GZIPed: 3.9Kb)
  • Is the successor of SWFObject 1.5, UFO and the Adobe Flash Player Detection Kit
  • Intends to unify all existing Flash Player embed methods and provide a new standard for embedding Adobe Flash Player content

Why should you use SWFObject?

SWFObject 2:

  • Is more optimized and flexible than any other Flash Player embed method around
  • Offers one solution for everybody: It shouldn't matter if you are an HTML, Flash, or JavaScript developer, there should be something in it for everyone
  • Breaks the cycle of being locked into vendor specific markup and promotes the use of web standards and alternative content
  • Uses unobtrusive JavaScript and JavaScript best practices
  • Is easy to use

The A List Apart article Flash Embedding Cage Match describes the full rationale behind SWFObject 2.

Why does SWFObject use JavaScript?

SWFObject 2 primarily uses JavaScript to overcome issues that cannot be solved by markup alone; it:

  • Detects the Flash Player version and determines whether Flash content or alternative content should be shown, to avoid that outdated Flash plug-ins break Flash content
  • Offers functionality to revert to alternative content in case of an outdated plug-in by means of a DOM manipulation (Note: if no Flash plug-in is installed the HTML object element automatically falls back to its nested alternative content)
  • Offers the option to use Adobe Express Install to download the latest Flash Player
  • Offers a JavaScript API to perform common Flash Player and Flash content related tasks

Should I use the static or dynamic publishing method?

SWFObject 2 offers two distinct methods to embed Flash Player content:

  1. The static publishing method embeds both Flash content and alternative content using standards compliant markup, and uses JavaScript to resolve the issues that markup alone cannot solve
  2. The dynamic publishing method is based on marked up alternative content and uses JavaScript to replace this content with Flash content if the minimal Flash Player version is installed and enough JavaScript support is available (similar like previous versions of SWFObject and UFO)

The advantages of the static publishing method are:

  1. The actual authoring of standards compliant markup is promoted
  2. Best embed performance
  3. The mechanism of embedding Flash content does not rely on a scripting language, so your Flash content can reach a significant bigger audience:
    • If you have the Flash plug-in installed, but have JavaScript disabled or a use a browser that doesn't support JavaScript, you will still be able to see your Flash content
    • Flash will now also run on a device like Sony PSP, which has very poor JavaScript support
    • Automated tools like RSS readers are able to pick up Flash content

The advantages of the dynamic publishing method are:

  1. It integrates very well with scripted applications and enables the use of dynamic variables (flashvars)
  2. It avoids click-to-activate mechanisms to activate active content in Internet Explorer 6/7 and Opera 9+. Please note that Microsoft has phased out most active content from its Internet Explorer browsers

How to embed Flash Player content using SWFObject static publishing

STEP 1: Embed both Flash content and alternative content using standards compliant markup

SWFObject's base markup uses the nested-objects method (with proprietary Internet Explorer conditional comments. See Flash Embedding Cage Match) to ensure the most optimal cross-browser support by means of markup only, while being standards compliant and supporting alternative content (See Flash Embed Test Suite):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject - step 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="780" height="420">
<param name="movie" value="myContent.swf" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="myContent.swf" width="780" height="420">
<!--<![endif]-->
<p>Alternative content</p>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>

</div>
</body>
</html>

NOTE: The nested-objects method requires a double object definition (the outer object targeting Internet Explorer and the inner object targeting all other browsers), so you need to define your object attributes and nested param elements twice.

Required attributes:

  • classid (outer object element only, value is always clsid:D27CDB6E-AE6D-11cf-96B8-444553540000)
  • type (inner object element only, value is always application/x-shockwave-flash)
  • data (inner object element only, defines the URL of a SWF)
  • width (both object elements, defines the width of a SWF)
  • height (both object elements, defines the height of a SWF)

Required param element:

  • movie (outer object element only, defines the URL of a SWF)

NOTE: We advise not to use the codebase attribute to point to the URL of the Flash plugin installer on Adobe's servers, because this is illegal according to the specifications which restrict its access to the domain of the current document only. We recommend the use of alternative content with a subtle message that a user can have a richer experience by downloading the Flash plugin instead.

How can you use HTML to configure your Flash content?

You can add the following often-used optional attributes to the object element:

  • id
  • name
  • class
  • align

You can use the following optional Flash specific param elements (more info):

Why should you use alternative content?

The object element allows you to nest alternative content inside of it, which will be displayed if Flash is not installed or supported. This content will also be picked up by search engines, making it a great tool for creating search-engine-friendly content. Summarizing, you should use alternative content when you like to create content that is accessible for people who browse the Web without plugins, create search-engine-friendly content or tell visitors that they can have a richer user experience by downloading the Flash plug-in.

STEP 2: Include the SWFObject JavaScript library in the head of your HTML page

The SWFObject library consists of one external JavaScript file. SWFObject will be executed as soon as it is read and will perform all DOM manipulations as soon as the DOM is loaded - for all browsers that support this, like IE, Firefox, Safari and Opera 9+ - or otherwise as soon as the onload event fires:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject - step 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<script type="text/javascript" src="swfobject.js"></script>

</head>
<body>
<div>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="780" height="420">
<param name="movie" value="myContent.swf" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="myContent.swf" width="780" height="420">
<!--<![endif]-->
<p>Alternative content</p>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</div>
</body>
</html>

STEP 3: Register your Flash content with the SWFObject library and tell SWFObject what to do with it

First add a unique id to the outer object tag that defines your Flash content. Second add the swfobject.registerObject method:

  1. The first argument (String, required) specifies the id used in the markup.
  2. The second argument (String, required) specifies the Flash player version your content is published for. It activates the Flash version detection for a SWF to determine whether to show Flash content or force alternative content by doing a DOM manipulation. While Flash version numbers normally consist of major.minor.release.build, SWFObject only looks at the first 3 numbers, so both "WIN 9,0,18,0" (IE) or "Shockwave Flash 9 r18" (all other browsers) will translate to "9.0.18". If you only want to test for a major version you can omit the minor and release numbers, like "9" instead of "9.0.0".
  3. The third argument (String, optional) can be used to activate Adobe express install and specifies the URL of your express install SWF file. Express install displays a standardized Flash plugin download dialog instead of your Flash content when the required plugin version is not available. A default expressInstall.swf file is packaged with the project. It also contains the corresponding expressInstall.fla and AS files (in the SRC directory) to let you create your own custom express install experience. Please note that express install will only fire once (the first time that it is invoked), that it is only supported by Flash Player 6.0.65 or higher on Win or Mac platforms, and that it requires a minimal SWF size of 310x137px.
  4. The fourth argument (JavaScript function, optional) can be used to define a callback function that is called on both success or failure of creating a Flash plug-in <object> on the page (see API documentation)
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
    <title>SWFObject - step 3</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <script type="text/javascript" src="swfobject.js"></script>

    <script type="text/javascript">
    swfobject
    .registerObject("myId", "9.0.115", "expressInstall.swf");
    </script>

    </head>
    <body>
    <div>

    <object id="myId" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="780" height="420">

    <param name="movie" value="myContent.swf" />
    <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data="myContent.swf" width="780" height="420">
    <!--<![endif]-->
    <p>Alternative content</p>
    <!--[if !IE]>-->
    </object>
    <!--<![endif]-->
    </object>
    </div>
    </body>
    </html>

TIPS

  • Use the SWFObject HTML and JavaScript generator to help you author your code
  • Just repeat steps 1 and 3 to embed multiple SWF files into one HTML page
  • The easiest way to reference the active object element is by using the JavaScript API: `swfobject.getObjectById(objectIdStr)

How to embed Flash Player content using SWFObject dynamic publishing

STEP 1: Create alternative content using standards compliant markup

SWFObject's dynamic embed method follows the principle of progressive enhancement and replaces alternative HTML content for Flash content when enough JavaScript and Flash plug-in support is available. First define your alternative content and label it with an id:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject dynamic embed - step 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>

<div id="myContent">
<p>Alternative content</p>
</div>

</body>
</html>

STEP 2: Include the SWFObject JavaScript library in the head of your HTML page

The SWFObject library consists of one external JavaScript file. SWFObject will be executed as soon as it is read and will perform all DOM manipulations as soon as the DOM is loaded - for all browsers that support this, like IE, Firefox, Safari and Opera 9+ - or otherwise as soon as the onload event fires:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject dynamic embed - step 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<script type="text/javascript" src="swfobject.js"></script>

</head>
<body>
<div id="myContent">
<p>Alternative content</p>
</div>
</body>
</html>

STEP 3: Embed your SWF with JavaScript

swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn) has five required and five optional arguments:

  1. swfUrl (String, required) specifies the URL of your SWF
  2. id (String, required) specifies the id of the HTML element (containing your alternative content) you would like to have replaced by your Flash content
  3. width (String, required) specifies the width of your SWF
  4. height (String, required) specifies the height of your SWF
  5. version (String, required) specifies the Flash player version your SWF is published for (format is: "major.minor.release" or "major")
  6. expressInstallSwfurl (String, optional) specifies the URL of your express install SWF and activates Adobe express install. Please note that express install will only fire once (the first time that it is invoked), that it is only supported by Flash Player 6.0.65 or higher on Win or Mac platforms, and that it requires a minimal SWF size of 310x137px.
  7. flashvars (Object, optional) specifies your flashvars with name:value pairs
  8. params (Object, optional) specifies your nested object element params with name:value pairs
  9. attributes (Object, optional) specifies your object's attributes with name:value pairs
  10. callbackFn (JavaScript function, optional) can be used to define a callback function that is called on both success or failure of creating a Flash plug-in <object> on the page (see API documentation)

NOTE: You can omit the optional parameters, as long as you don't break the parameter order. If you don't want to use an optional parameter, but would like to use a following optional parameter, you can simply pass false as its value. For the flashvars, params and attributes JavaScript Objects, you can also pass an empty object instead: {}.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject dynamic embed - step 3</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="swfobject.js"></script>

<script type="text/javascript">
swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0");
</script>

</head>
<body>
<div id="myContent">
<p>Alternative content</p>
</div>
</body>
</html>

How can you configure your Flash content?

You can add the following often-used optional attributes to the object element:

  • id (NOTE: when undefined, the object element automatically inherits the id from the alternative content container element)
  • align
  • name
  • styleclass (see note about class)
  • class

Note: class is a reserved ECMA4 keyword and will throw errors in Internet Explorer unless it is surrounded by quotation marks (e.g. "class" or 'class'). For this reason, swfobject provides the styleclass keyword as a safe alternative syntax for class; if you use styleclass, swfobject will automatically insert it as class for you.

Example:

var attributes = {
id
: "myId",
align
: "left",
styleclass
: "myclass"
};

If you would rather use class instead of styleclass, wrap the word class in quotes like this:

var attributes = {
id
: "myId",
align
: "left",
"class": "myclass"
};

You can use the following optional Flash specific param elements (more info):

How do you use JavaScript Objects to define your flashvars, params and object's attributes?

You can best define JavaScript Objects using the Object literal notation, which looks like:

<script type="text/javascript">

var flashvars = {};
var params = {};
var attributes = {};

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

You can add your name:value pairs while you define an object (note: please make sure not to put a comma behind the last name:value pair inside an object)

<script type="text/javascript">

var flashvars = {
name1
: "hello",
name2
: "world",
name3
: "foobar"
};
var params = {
menu
: "false"
};
var attributes = {
id
: "myDynamicContent",
name
: "myDynamicContent"
};

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

Or add properties and values after its creation by using a dot notation:

<script type="text/javascript">

var flashvars = {};
flashvars
.name1 = "hello";
flashvars
.name2 = "world";
flashvars
.name3 = "foobar";

var params = {};
params
.menu = "false";

var attributes = {};
attributes
.id = "myDynamicContent";
attributes
.name = "myDynamicContent";

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

Which can also be written as (the less readable shorthand version for the die-hard scripter who love one-liners):

<script type="text/javascript">

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", {name1:"hello",name2:"world",name3:"foobar"}, {menu:"false"}, {id:"myDynamicContent",name:"myDynamicContent"});

</script>

If you don't want to use an optional argument you can define it as false or as an empty Object (NOTE: from SWFObject 2.1 onwards you can also use null or 0):

<script type="text/javascript">

var flashvars = false;
var params = {};
var attributes = {
id
: "myDynamicContent",
name
: "myDynamicContent"
};

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

The flashvars Object is a shorthand notation that is there for your ease of use. You could potentially ignore it and specify your flashvars via the params Object:

<script type="text/javascript">

var flashvars = false;
var params = {
menu
: "false",
flashvars
: "name1=hello&name2=world&name3=foobar"
};
var attributes = {
id
: "myDynamicContent",
name
: "myDynamicContent"
};

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

TIPS

SWFObject 1.5 to SWFObject 2 migration tips

  1. SWFObject 2 is NOT backwards compatible with SWFObject 1.5
  2. It is now preferred to insert all script blocks in the head of your HTML page. Adding your scripts in the body of your page may have visual impact (e.g. flashes of replaced alternative content), because your JavaScript code will be executed in a later stage (the exact impact depends on your implementation)
  3. The library itself is now written in lowercase: swfobject instead of SWFObject
  4. Methods can only be accessed via the library (instead via a SWFObject instance in SWFObject 1.5)
  5. The JavaScript API is entirely different and more elaborate
  6. SWFObject 2 replaces your entire alternative HTML content block, including the referenced HTML container element, for Flash content when enough JavaScript and Flash support is available, while SWFObject 1.5 only replaces the content inside the referenced HTML container. When you don't specify an id attribute, the object element will automatically inherit the id of the HTML container element of your alternative content.

UFO to SWFObject 2 migration tips

  1. SWFObject 2 replaces your entire alternative HTML content block, including the referenced HTML container element, for Flash content when enough JavaScript and Flash support is available, while UFO only replaces the content inside the referenced HTML container. When you don't specify an id attribute, the object element will automatically inherit the id of the HTML container element of your alternative content.
  2. UFO's setcontainercss feature has not been incorporated in SWFObject 2, however it can easily be replicated by using the SWFObject JavaScript API, see: swfobject.createCSS(selStr, declStr)

Does SWFObject 2 support MIME type application/xhtml+xml?

SWFObject 2 does NOT support XML MIME types, which is a design decision.

There are a number of reasons why we are not supporting this:

  • Only a very small (non-significant) amount of web authors is using it
  • We are unsure if it is the direction to go. Internet Explorer does not support it and all other major browser vendors are aiming their arrows at a new standard way of HTML parsing (with HTML 5), which departs from the current W3C vision of parsing HTML as XML
  • We save a considerate amount of file size and effort (testing, issue resolving) by not supporting it

Tutorials (beginner level)

Comments

The comments functionality on this wiki has been switched off to avoid spam and abuse.

If you have any questions/comments about SWFObject or its documentation, or have problems with an implementation:

  1. Please make sure you have read our FAQ
  2. Use the SWFObject discussion group

If you find any bugs or want to request a future enhancement, you can fill in an issue report on the SWFObject issues page

Posted by 1010
반응형

Using the Console

The JavaScript Console provides two primary functions for developers testing web pages and applications:

  • A place to log diagnostic information using methods provided by the Console API, such as console.log(), or console.profile().
  • A shell prompt where you can enter commands and interact with the document and the Chrome DevTools. You can evaluate expressions directly in the Console, and can also use the methods provided by the Command Line API, such as $() command for selecting elements, or profile() to start the CPU profiler.

This documentation provides an overview and common uses of these two APIs. You can also browse the Console API and Command Line API reference guides.

Basic operation

Opening the Console

The JavaScript Console is available in two modes within Chrome DevTools: the primary Console tab, or as a split-view you can display while on another tab (such as Elements or Sources).

To open the Console tab, do one of the following:

  • Use the keyboard shortcut Command - Option - J (Mac) or Control -Shift -J (Windows/Linux).
  • Select View > Developer > JavaScript Console.

Console panel view

To toggle a split-view of the Console on another tab, press the Esc key on your keyboard, or click the Show/Hide Console button in the bottom left corner of the Chrome DevTools window. In the following screenshot the Console split-view is shown with the Elements panel.

Console split-view

Clearing the console history

To clear the console's history, do one of the following:

  • Right-click or Ctrl-click anywhere in the Console and choose Clear Console from the context menu that appears.
  • Enter the clear() Command Line API at the shell prompt.
  • Invoke console.clear() Console API from JavaScript.
  • Use the keyboard shortcut ⌘K or ⌃L (Mac) Control - L (Windows and Linux).

By default, the console history is cleared when you navigate to another page. You can change this behavior by enabling Preserve log upon navigation in the Console area of the Settings dialog (see Console preferences).

Console settings

The Console has two global settings you can modify in the General tab of the DevTools Settings dialog:

  • Log XMLHTTPRequests—determines if each XMLHTTPRequest is logged to the Console panel.
  • Preserve log upon navigation—determines if console history for the current page is preserved when you navigate to another page. By default, both of these settings are disabled.

You can also change these settings by right-clicking anywhere in the Console to bring up the context menu.

Console panel view

Using the Console API

The Console API is collection of methods provided by the global console object defined by DevTools. One of the API's main purposes is to log information (such as a property value, or an entire objects or DOM element) to the console while your application is running. You can also group output visually in the console to reduce visual clutter.

Writing to the console

The console.log() method takes one or more expressions as parameters and writes their current values to the console. For example:

var a = document.createElement('p');
a
.appendChild(document.createTextNode('foo'));
a
.appendChild(document.createTextNode('bar'));
console
.log("Node count: " + a.childNodes.length);

Console log output

Instead of concatenating expressions together with the "+" operator (as shown above), you can put each in its own method parameter and they will be joined together in a space-delimited line.

console.log("Node count:", a.childNodes.length, "and the current time is:", Date.now());

Console log output

Errors and warnings

The console.error() method displays a red icon along with the message text, which is colored red.

function connectToServer() {
console
.error("Error: %s (%i)", "Server is not responding",500);
}
connectToServer
();

The console.warn() method displays a yellow warning icon with the message text.

if(a.childNodes.length < 3 ) {
console
.warn('Warning! Too few nodes (%d)', a.childNodes.length);
}

Example of console.warn()

Assertions

The console.assert() method conditionally displays an error string (its second parameter) only if its first parameter evaluates to false. For instance, in the following example an error message is written to the console only if the number of child nodes belonging to the list element is greater than 500.

console.assert(list.childNodes.length < 500, "Node count is > 500");

Example of console.assert()

Filtering console output

You can quickly filter console output by its severity level--errors, warning, or standard log statements--by selecting one of the filter options along the bottom of the Console, as shown below.

Only show console.error() output

Filter options:

  • All—Shows all console output.
  • Errors—Only show output from console.error()
  • Warnings—Only show output from console.warn()
  • Logs—Only show output from console.log(), console.info() and console.debug().
  • Debug—Only show output from console.timeEnd() and other console output.

Grouping output

You can visually group related console output statements together in the console with the console.group() and groupEnd() commands.

var user = "jsmith", authenticated = false;
console
.group("Authentication phase");
console
.log("Authenticating user '%s'", user);
// authentication code here...
if (!authenticated) {
console
.log("User '%s' not authenticated.", user)
}
console
.groupEnd();

Logging group example

You can also nest logging groups. In the following example a logging group is created for the authentication phase of a login process. If the user is authenticated, a nested group is created for the authorization phase.

var user = "jsmith", authenticated = true, authorized = true;
// Top-level group
console
.group("Authenticating user '%s'", user);
if (authenticated) {
console
.log("User '%s' was authenticated", user);
// Start nested group
console
.group("Authorizing user '%s'", user);
if (authorized) {
console
.log("User '%s' was authorized.", user);
}
// End nested group
console
.groupEnd();
}
// End top-level group
console
.groupEnd();
console
.log("A group-less log trace.");

Nested logging group example

To create a group that is initially collapsed, use console.groupCollapsed() instead of console.group(), as shown below:

console.groupCollapsed("Authenticating user '%s'", user);
if (authenticated) {
...
}

Initially collapsed group

String substitution and formatting

The first parameter you pass to any of the console's logging methods (log() or error(), for example) may contain one or more format specifiers. A format specifier consists of a % symbol followed by a letter that indicates the formatting that should be applied to the inserted value (%s for strings, for example). The format specifier identifies where to substitute a value provided by a subsequent parameter value.

The following example using the %s (string) and %d (integer) formatters to insert values into the output string.

console.log("%s has %d points", "Sam", "100");

This would result in "Sam has 100 points" being logged to the console.

The following table lists the supported format specifiers and the formatting they apply:

Format specifier Description
%s Formats the value as a string.
%d or %i Formats the value as an integer.
%f Formats the object as a floating point value.
%o Formats the value as an expandable DOM element (as in the Elements panel).
%O Formats the value as an expandable JavaScript object.
%c Applies CSS style rules to output string specified by the second parameter.

In the following example the %d format specifier is substituted with the value of document.childNodes.length and formatted as an integer; the %f format specifier is substituted with the value returned by Date.now(), which is formatted as a floating point number.

console.log("Node count: %d, and the time is %f.", document.childNodes.length, Date.now());

Using format specifiers

Formatting DOM elements as JavaScript objects

By default, when you log a DOM element to the console it's displayed in an XML format, as in the Elements panel:

console.log(document.body.firstElementChild)

You can also log an element's JavaScript representation with the console.dir() method:

console.dir(document.body.firstElementChild);

Equivalently, you can us the %O format specifier with console.log():

console.log("%O", document.body.firstElementChild);

Styling console output with CSS

You use the %c format specifier to apply custom CSS rules to any string you write to the Console with console.log() or related methods.

console.log("%cThis will be formatted with large, blue text", "color: blue; font-size:18pt");

Styling console output with CSS

Measuring how long something takes

You can use the console.time() and console.timeEnd() methods to measure how long a function or operation in your code takes to complete. You call console.time() at the point in your code where you want to start the timer and console.timeEnd() to stop the timer. The elapsed time between these two calls is displayed in the console.

console.time("Array initialize");
var array= new Array(1000000);
for (var i = array.length - 1; i >= 0; i--) {
array
[i] = new Object();
};
console
.timeEnd("Array initialize");

Example of using console.time() and timeEnd()

Marking the Timeline

The Timeline panel gives you a complete overview of where time is spent when loading and using your web app or page. The console.timeStamp() method marks the Timeline at the moment it was executed. This provides an easy way to correlate events in your application with other browser-related events, such as layout or paints.

In the following example the Timeline is marked when the application enters the AddResult() function's implementation.

function AddResult(name, result) {
console
.timeStamp("Adding result");
var text = name + ': ' + result;
var results = document.getElementById("results");
results
.innerHTML += (text + "<br>");
}

As shown in the following screenshot, the timeStamp() command annotates the Timeline in the following places:

  • A yellow vertical line in the Timeline's summary and detail views.
  • A record is added to the list of recorded events.

Timeline showing custom timestamp

Setting breakpoints in JavaScript

You can start a debugging session from your JavaScript code by calling the debugger command. For instance, in the following example the JavaScript debugger is opened when an object's brightness() function is invoked:

brightness : function() {
debugger;
var r = Math.floor(this.red*255);
var g = Math.floor(this.green*255);
var b = Math.floor(this.blue*255);
return (r * 77 + g * 150 + b * 29) >> 8;
}

Example of using debugger command

Using the Command Line API

In addition to being a place where you can log information from your application, the Console is also a shell prompt where you can directly evaluate expressions or issue commands provided by the Command Line API. This API provides the following features:

  • Convenience functions for selecting DOM elements
  • Methods for controlling the CPU profiler
  • Aliases for a number of Console API methods
  • Monitoring events
  • View event listeners registered on objects

Evaluating expressions

The Console attempts to evaluate any JavaScript expression you enter at the shell prompt, upon pressing the Return or Enter key. The Console provides auto-completion and tab-completion. As you type expressions, property names are automatically suggested. If there are multiple properties with the same prefix, pressing the Tab key cycles through them. Pressing the right arrow key accepts the current suggestion. The current suggestion is also accepted by pressing the Tab key if there is only one matched property.

To enter a multi-line expression at the shell prompt (such as a function definition) press Shift+Enter between lines.

Selecting elements

The Command Line API provides several methods to access DOM elements in your application. For example, the $() method returns the first element that matches the specified CSS selector, just like document.querySelector(). For instance, the following code returns the element with the ID "loginBtn".

$('#loginBtn');

The $$() command returns an array of all the elements that match the specified CSS selector, just like document.querySelectorAll(). For instance, the following displays selects all <button> elements with the CSS class "loginBtn":

$$('button.loginBtn');

Lastly, the x() method takes an XPath path as a parameter and returns an array of all elements that match the specified path. The following returns all the <script> elements that are children of the <body> tag:

$x('/html/body/script');

Inspecting DOM elements and JavaScript heap objects

The inspect() method takes a DOM element reference (or JavaScript reference) as a parameter and displays the element or object in the appropriate panel—the Elements panel for DOM elements, or the Profile panel for a JavaScript object.

For example, in the following screenshot the $() function is used to get a reference to an <li> element. Then the last evaluated expression property ($_) is passed to inspect() to open that element in the Elements panel.

Accessing recently selected elements and objects

Often when testing you'll select DOM elements—either directly in the Elements panel or using the Selection tool (magnifying glass)—so that you can further inspect the element. Or, when analyzing a memory snapshot in the Profiles panel, you might select a JavaScript object to further inspect it.

The Console remembers the last five elements (or heap objects) you've selected and makes them available as properties named $0, $1, $2, $3 and $4. The most recently selected element or object is available as $0, the second most as $1, and so forth.

The following screenshot shows the values of these properties after selecting three different elements in turn from the Elements panel:

Recently selected elements

Monitoring events

The monitorEvents() command monitors an object for one or more specified events. When an event occurs on the monitored object, the corresponding Event object is logged to the Console. You specify the object and the events you want to monitor on that object. For example, the following code enables event monitoring for every "resize" event on the global window object.

monitorEvents(window, "resize");

Monitoring window resize events

To monitor several events, you can pass an array of event names as the second parameter. The code below monitors both "mousedown" and "mouseup" events on the body of the document.

monitorEvents(document.body, ["mousedown", "mouseup"]);

You can also pass one of the supported "event types" that DevTools maps to a set of actual event names. For example, the "touch" event type cause DevTools to monitor "touchstart", "touchend", "touchmove", and "touchcancel" events on the target object.

monitorEvents($('#scrollBar'), "touch");

See monitorEvents() in the Console API Reference for a list of supported event types.

To stop monitoring events call unmonitorEvents(), passing the object to stop monitoring.

unmonitorEvents(window);

Controlling the CPU profiler

You can create JavaScript CPU profiles from the command line with the profile() and profileEnd() commands. You can optionally specify a name that's applied to the profile you create.

For example, the following shows an example of creating a new profile with the default name:

The new profile appears in the Profiles panel under the name "Profile 1":

If you specify a label for the new profile, it is used as the new profile's heading. If you create multiple profiles with the same name, they are grouped as individual runs under the same heading:

The result in the Profiles panel:

CPU profiles can be nested, for example:

profile("A");
profile
("B");
profileEnd
("B")
profileEnd
("A")

The calls to stop and start profiling do not need be properly nested. For example, the following works the same as the previous example:

profile("A");
profile
("B");
profileEnd
("A");
profileEnd
("B");

 

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