Adobe Flex creating polygon - actionscript-3

How to create a polygon in Adobe flex 3.0

You draw a bunch of lines connecting the points of the polygon.
As a quick example:
function drawPolygon(first, ... rest) {
graphics.moveTo(first.x, first.y);
for(var i = 0; i < rest.length; i++) {
graphics.lineTo(rest[i].x, rest[i].y);
}
graphics.lineTo(first.x, first.y);
}
May be some minor syntax errors, but you get the idea. You'd call it by passing a bunch of Point objects indicating the points of the polygon.

Try this sample
<?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"
xmlns:esri="http://www.esri.com/2008/ags">
<fx:Script>
<![CDATA[
import com.esri.ags.Graphic;
import com.esri.ags.SpatialReference;
import com.esri.ags.Units;
import com.esri.ags.geometry.Geometry;
import com.esri.ags.geometry.MapPoint;
import com.esri.ags.geometry.Polygon;
import com.esri.ags.geometry.Polyline;
import com.esri.ags.utils.GeometryUtil;
import mx.utils.StringUtil;
private const sr:SpatialReference = new SpatialReference(4326);
protected function onCreatePolyline(event:MouseEvent):void
{
addMessage("Create polyline clicked");
var pts:Array = new Array();
for (var i:int; i < 10; i++) // add 10 random points to path
{
var pt:MapPoint = new MapPoint(Math.random()*10000, Math.random()*10000, sr);
pts.push(pt);
}
var pl:Polyline = new Polyline(new Array(pts), sr);
var lengths:Array = GeometryUtil.geodesicLengths(new Array(pl), Units.KILOMETERS);
if (lengths != null && lengths.length > 0)
{
addMessage(StringUtil.substitute("polyline created with length {0} km", lengths[0]));
}
addGraphic(pl);
}
protected function onCreatePolygon(event:MouseEvent):void
{
addMessage("Create polygon clicked");
var pts:Array = new Array();
for (var i:int; i < 10; i++) // add 10 random points to ring
{
var pt:MapPoint = new MapPoint(Math.random()*10000, Math.random()*10000, sr);
pts.push(pt);
}
var pg:Polygon = new Polygon(new Array(pts), sr);
var areas:Array = GeometryUtil.geodesicAreas(new Array(pg), Units.SQUARE_KILOMETERS);
if (areas != null && areas.length > 0)
{
addMessage(StringUtil.substitute("polygon created with area {0} kmĀ²", Math.abs(areas[0])));
}
addGraphic(pg);
}
private function addMessage(message:String):void
{
log.text = StringUtil.substitute("> > > {0}\n{1}", message, log.text);
}
private function addGraphic(geometry:Geometry):void
{
var gr:Graphic = new Graphic(geometry);
grLayer.clear();
var grId:String = grLayer.add(gr);
addMessage(StringUtil.substitute("graphic added with id='{0}'", grId));
map.initialExtent = geometry.extent;
map.zoomToInitialExtent();
}
]]>
</fx:Script>
<s:layout>
<s:VerticalLayout gap="10"
paddingBottom="10"
paddingLeft="10"
paddingRight="10"
paddingTop="10"/>
</s:layout>
<s:Button label="Create polyline"
click="onCreatePolyline(event)"/>
<s:Button label="Create polygon"
click="onCreatePolygon(event)"/>
<s:TextArea id="log"
width="100%"
height="100%"/>
<esri:Map id="map"
zoomSliderVisible="false"
minHeight="200"
width="100%">
<esri:GraphicsLayer id="grLayer" />
</esri:Map>
</s:Application>

Related

Export flex chart and datagrid to excel

I need to export a pie chart and a datagrid in flex 4.5 to Microsoft Excel format. I was able to export the datagrid using as3xls. But it doesn't allow to export any chart or even add an image to excel file. Can anyone recommend me a way of doing this?
As far as I know there is no way to export a chart to Excel by means of existing libraries.
I would like to suggest you one specific way to do it. We all well know that current Office files are stored as collections of XML structures. The files are packed as a zip-archive. If you have a look at this stuff, you can see that it is possible just to manipulate some lines in this files to get any table, any chart, any picture you'd like to have.
To do it in Flex you need basic XML-structures and some library to be able to zip the result.
I have used Nochump component to have access to zip-functions.
Here you can read about the structure of Excel-files.
Here are some pictures which show you a possible result you can achieve with this method.
Regarding the application, you should know which files have to be patched:
sheet1.xml has information about cells of your sheet
sharedStrings.xml is a dictionary of all strings in the file
chart1.xml is a description of your chart - you should change only
ranges of your data.
To get it working I created an XML-structure with description of the Excel-file-tree. The actual XML-files of this file-tree I put to my projects folder. Then I read all the files to an ArrayCollection and manipulated data of three of them.
After all I packed them to a zip-archive and let user save it to the PC.
Here is the source code:
<?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"
minWidth="955" minHeight="600"
creationComplete="onCreationComplete(event)">
<fx:Declarations>
<fx:XML id="fileTree" xmlns="">
<root id=''>
<folder id='_rels'>
<file id='.rels'/>
</folder>
<folder id='docProps'>
<file id='app.xml'/>
<file id='core.xml'/>
</folder>
<folder id='xl'>
<folder id='_rels'>
<file id='workbook.xml.rels'/>
</folder>
<folder id='charts'>
<file id='chart1.xml'/>
</folder>
<folder id='drawings'>
<folder id='_rels'>
<file id='drawing1.xml.rels'/>
</folder>
<file id='drawing1.xml'/>
</folder>
<folder id='theme'>
<file id='theme1.xml'/>
</folder>
<folder id='worksheets'>
<folder id='_rels'>
<file id='sheet1.xml.rels'/>
</folder>
<file id='sheet1.xml'/>
</folder>
<file id='sharedStrings.xml'/>
<file id='styles.xml'/>
<file id='workbook.xml'/>
</folder>
<file id='[Content_Types].xml'/>
</root>
</fx:XML>
</fx:Declarations>
<fx:Script>
<![CDATA[
import flash.utils.ByteArray;
import mx.collections.ArrayCollection;
import mx.collections.XMLListCollection;
import mx.controls.Alert;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.events.FlexEvent;
import mx.rpc.xml.SimpleXMLDecoder;
import nochump.util.zip.*;
private const CELL_LETTERS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private var xmlLoader:URLLoader = new URLLoader();
private var loaderItemId:int = 0;
private var rootPath:String = "com/excelchart/xmlsource/";
private var xlsxFiles:ArrayCollection = new ArrayCollection();
[Bindable]private var dp:ArrayCollection = new ArrayCollection([
{party:"SPD", y2009:23, y2005:34.2 },
{party:"CDU", y2009:27.3, y2005:27.8 },
{party:"FDP", y2009:14.6, y2005:9.8 },
{party:"The Left Party", y2009:11.9, y2005:8.7 },
{party:"A90/The Greens", y2009:10.7, y2005:8.1 },
{party:"CSU", y2009:6.5, y2005:7.4 },
{party:"Others", y2009:6, y2005:3.9 }]);
protected function onCreationComplete(event:FlexEvent):void
{
init();
traverseXMLList(fileTree, 0, "");
processNextNode();
}
private function traverseXMLList(xml:XML, depth:int, parentPath:String):void
{
var path:String = (parentPath == "") ? xml.#id : parentPath + "/" + xml.#id;
var nodeType:String = xml.name().localName;
xlsxFiles.addItem({name:xml.#id.toString(), type:nodeType, path:path});
for each (var item:XML in xml.children())
traverseXMLList(item, depth + 1, path);
}
private function packZip():void
{
var zipEntry:ZipEntry;
var fileName:String;
var fileData:ByteArray = new ByteArray();
var zipOut:ZipOutput = new ZipOutput();
for (var i:int = 0; i < xlsxFiles.length; i++)
{
var obj:Object = xlsxFiles.getItemAt(i);
if (obj.type == "file")
{
fileName = obj.path;
zipEntry = new ZipEntry(fileName);
fileData.clear();
fileData.writeUTFBytes(obj.content);
zipOut.putNextEntry(zipEntry);
zipOut.write(fileData);
zipOut.closeEntry();
}
}
// end the zip
zipOut.finish();
var file:FileReference = new FileReference();
file.save(zipOut.byteArray, "chart.xlsx");
}
private function init():void
{
xmlLoader.addEventListener(Event.COMPLETE, onXmlLoaderComplete);
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, onXmlLoaderIOError);
}
private function loadXML():void
{
xmlLoader.load(new URLRequest(rootPath + xlsxFiles.getItemAt(loaderItemId).path));
}
private function onXmlLoaderComplete(event:Event):void
{
xlsxFiles.getItemAt(loaderItemId).content = (event.currentTarget as URLLoader).data;
processNextNode();
}
private function processNextNode():void
{
if (xlsxFiles.length > loaderItemId + 1)
{
loaderItemId++;
if (xlsxFiles.getItemAt(loaderItemId).type == "file")
loadXML();
else
processNextNode();
}
else
this.btnMakeZip.enabled = true;
}
private function onXmlLoaderIOError(evt:IOErrorEvent):void
{
Alert.show("error!");
}
protected function onMakeZipClick(event:MouseEvent):void
{
parseDataGrid();
packZip();
}
protected function isString(input:String):Boolean
{
return isNaN(Number(input));
}
protected function parseDataGrid():void
{
function getStringId(str:String):int
{
var result:int = -1;
for (var i:int = 0; i < stringDictionary.length; i++)
if (stringDictionary.getItemAt(i) == str)
{
result = i;
break;
}
if (result == -1)
{
stringDictionary.addItem(str);
result = stringDictionary.length - 1;
}
return result;
}
//find sheet1 xml
var sheet1XML:XML;
var xlsxFilesItemId:int;
for (i = 0; i < xlsxFiles.length; i++)
if (xlsxFiles.getItemAt(i).name == "sheet1.xml")
{
sheet1XML = new XML(xlsxFiles.getItemAt(i).content);
xlsxFilesItemId = i;
break;
}
//define the size of the DG
var dgHeight:int = myGrid.dataProvider.length;
var dgWidth:int = myGrid.columns.length;
//namespaces for elements
var mainNS:Namespace = new Namespace("http://schemas.openxmlformats.org/spreadsheetml/2006/main");
var x14acNS:Namespace = new Namespace("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
default xml namespace = mainNS;
sheet1XML.addNamespace(x14acNS);
sheet1XML.dimension.#ref = "A1:" + CELL_LETTERS.charAt(dgWidth) + (dgHeight + 1).toString();
//delete nodes from sheet1XML.sheetData
var sheetDataRowCollection:XMLListCollection = new XMLListCollection(sheet1XML.sheetData.row);
sheetDataRowCollection.removeAll();
//create a String dictionary
var stringDictionary:ArrayCollection = new ArrayCollection();
var stringId:int = 0;
var cellNode:XML, rowNode:XML, value:String, cellAddress:String;
var i:int, j:int;
//add head information
rowNode = new XML();
rowNode.addNamespace(mainNS);
rowNode.addNamespace(x14acNS);
rowNode = <row r="1" spans="1:3"/>;
rowNode.#x14acNS::dyDescent = "0.25";
for (j = 0; j < dgWidth; j++)
{
value = (((myGrid.columns as ArrayList).getItemAt(j) as GridColumn).headerText).toString();
cellAddress = CELL_LETTERS.charAt(j) + "1";
cellNode = new XML();
cellNode = <c r={cellAddress} t="s"><v>{getStringId(value).toString()}</v></c>;
rowNode = rowNode.appendChild(cellNode);
}
sheetDataRowCollection.addItem(rowNode);
//traverse through DG
for (i = 0; i < dgHeight; i++)
{
rowNode = new XML();
rowNode.addNamespace(mainNS);
rowNode.addNamespace(x14acNS);
rowNode = <row r={i + 2} spans="1:3"/>;
rowNode.#x14acNS::dyDescent = "0.25";
for (j = 0; j < dgWidth; j++)
{
value = (myGrid.dataProvider.getItemAt(i)[((myGrid.columns as ArrayList).getItemAt(j) as GridColumn).dataField]).toString();
cellAddress = CELL_LETTERS.charAt(j) + (i+2).toString();
cellNode = new XML();
if (isString(value))
cellNode = <c r={cellAddress} t="s"><v>{getStringId(value).toString()}</v></c>;
else
cellNode = <c r={cellAddress}><v>{value}</v></c>;
rowNode = rowNode.appendChild(cellNode);
}
sheetDataRowCollection.addItem(rowNode);
}
//save sheet1 to xlsxFiles
xlsxFiles.getItemAt(xlsxFilesItemId).content = sheet1XML;
//sharedStrings
var sharedStringsXML:XML;
for (i = 0; i < xlsxFiles.length; i++)
if (xlsxFiles.getItemAt(i).name == "sharedStrings.xml")
{
sharedStringsXML = new XML(xlsxFiles.getItemAt(i).content);
xlsxFilesItemId = i;
break;
}
//delete nodes from sharedStrings.xml
var sharedStringsCollection:XMLListCollection = new XMLListCollection(sharedStringsXML.si);
sharedStringsCollection.removeAll();
//fill the sharedStrings XML
sharedStringsXML.#count = stringDictionary.length;
sharedStringsXML.#uniqueCount = stringDictionary.length;
//var siNode:XML;
for each (var str:String in stringDictionary)
sharedStringsXML.appendChild(<si><t>{str}</t></si>);
//save sharedStrings to xlsxFiles
xlsxFiles.getItemAt(xlsxFilesItemId).content = sharedStringsXML;
//chart1
var chart1XML:XML;
for (i = 0; i < xlsxFiles.length; i++)
if (xlsxFiles.getItemAt(i).name == "chart1.xml")
{
chart1XML = new XML(xlsxFiles.getItemAt(i).content);
xlsxFilesItemId = i;
break;
}
var catLetter:String = CELL_LETTERS.charAt(cbCategories.selectedIndex);
var catAddress:String = "Tabelle1!$" + catLetter + "$2:$" + catLetter + "$" + (dgHeight + 1).toString();
var valLetter:String = CELL_LETTERS.charAt(cbValues.selectedIndex);
var valAddress:String = "Tabelle1!$" + valLetter + "$2:$" + valLetter + "$" + (dgHeight + 1).toString();
default xml namespace = new Namespace("c", "http://schemas.openxmlformats.org/drawingml/2006/chart");
chart1XML.chart.plotArea.pieChart.ser.cat.strRef.f = catAddress;
chart1XML.chart.plotArea.pieChart.ser.val.numRef.f = valAddress;
xlsxFiles.getItemAt(xlsxFilesItemId).content = chart1XML;
//switch back to the default namespace
default xml namespace = new Namespace("");
}
private function onBtnRefresh():void
{
this.mySeries.nameField = cbCategories.selectedItem.dataField;
this.mySeries.field = cbValues.selectedItem.dataField;
}
]]>
</fx:Script>
<s:HGroup x="100" y="50">
<s:VGroup>
<s:DataGrid id="myGrid" width="360" dataProvider="{dp}">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="party" headerText="Party"/>
<s:GridColumn dataField="y2005" headerText="2005" width="90"/>
<s:GridColumn dataField="y2009" headerText="2009" width="90"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
<s:HGroup verticalAlign="bottom">
<s:Label text="Categories:" width="70"/>
<s:ComboBox id="cbCategories" dataProvider="{myGrid.columns}" labelField="headerText" selectedIndex="0"/>
</s:HGroup>
<s:HGroup verticalAlign="bottom">
<s:Label text="Values:" width="70"/>
<s:ComboBox id="cbValues" dataProvider="{myGrid.columns}" labelField="headerText" selectedIndex="1"/>
</s:HGroup>
<s:HGroup>
<s:Button id="btnRefresh" label="Bild Chart" click="onBtnRefresh()"/>
<s:Button id="btnMakeZip" label="Export" enabled="false" click="onMakeZipClick(event)"/>
</s:HGroup>
</s:VGroup>
<mx:PieChart id="myChart" width="281" height="277" dataProvider="{dp}" showDataTips="true">
<mx:series>
<mx:PieSeries id="mySeries" field="y2005" nameField="party" labelPosition="inside" explodeRadius=".12" />
</mx:series>
</mx:PieChart>
<mx:Legend dataProvider="{myChart}"/>
</s:HGroup>
</s:Application>
I hope it can help you.
Thanks for the interesting question!

Cannot correctly resize an image via action script

Hi I am trying to add an image when I click on a thumbnail.
I know I have to use a listener (Event.COMPLETE ?), but the image is not resizing correctly when I rotate the tablet.
I believe the problem is that I cannot resize the image within the addImage1() function, as the image has not yet loaded, but I cannot use newImg.width within the listener function to reset the image width.
Any help would be most appreciated.
Code follows:-)
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="ZOOM Pictues with Tap"
resize="view1_resizeHandler(event)">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.events.ResizeEvent;
public var hasImageBeenAdded:Boolean = false;
private var imageLastWidth:Number;
private var imageLastHeight:Number;
private var zoomFactor:Number;
private var imageNumber:Number;
private var rhsKeepWidth:int;
private var rhsKeepHeight:int;
private var rhsKeep:Boolean = false;
protected function view1_resizeHandler(event:ResizeEvent):void
{
if(rhsKeepWidth > rhsKeepHeight) // Was Landscape is now Portrait
{
var tmpWidth2:int = rhsKeepWidth;
var tmpHeight2:int = rhsKeepHeight;
rhsKeepWidth = tmpHeight2-lhs.width;
rhsKeepHeight = tmpWidth2+lhs.width;
}
else //Was Portrait is now Landscape
{
var tmpWidth1:int = rhsKeepWidth;
var tmpHeight1:int = rhsKeepHeight;
rhsKeepWidth = tmpHeight1-lhs.width;
rhsKeepHeight = tmpWidth1+lhs.width;
}
addImage1();
}
protected function removeAllImages():void
{
var totalElements : int = rhs.numElements;
for(var i:int=totalElements-1;i>=0;i--)
{
rhs.removeElementAt(i);
}
}
private function onImageLoaded(e:Event):void
{
var zoomFactor1:Number;
var zoomFactor2:Number;
imageLastWidth = e.target.sourceWidth;
imageLastHeight = e.target.sourceHeight;
if(rhsKeep != true) //Need to set the rhs VGroup dimensions
{
rhs.width = hGroup1.width-lhs.width;
rhs.height = hGroup1.height;
rhsKeep = true;
rhsKeepWidth = rhs.width;
rhsKeepHeight = rhs.height;
}
zoomFactor1 = rhsKeepWidth/imageLastWidth;
zoomFactor2 = rhsKeepHeight/imageLastHeight;
if(zoomFactor1 < zoomFactor2)
{
zoomFactor = zoomFactor1;
}
else
{
zoomFactor = zoomFactor2;
}
trace("zoomFactor=" + zoomFactor);
}
public function addImage1():void
{
var i:int;
var newImg:Image = new Image();
removeAllImages();
newImg.source = "images/1.jpg";
newImg.x = 0;
newImg.y = 0;
newImg.addEventListener(Event.COMPLETE,onImageLoaded);
rhs.addElementAt(newImg,0);
hasImageBeenAdded = true;
imageNumber = 1;
trace("Image Width= " + newImg.width);
newImg.scaleX = newImg.scaleY = zoomFactor;
}
]]>
</fx:Script>
<s:HGroup id="hGroup1" width="100%" height="100%">
<s:Scroller id="scrollerL" height="100%">
<s:VGroup id="lhs" width="15%" height="100%" gap="10"
horizontalAlign="center" verticalAlign="top">
<s:Image width="100" height="100" source="thumbs/1.jpg" click="addImage1()"/>
</s:VGroup>
</s:Scroller>
<s:Scroller id="scroller1" height="100%" width="100%">
<s:VGroup id="rhs" height="100%">
</s:VGroup>
</s:Scroller>
</s:HGroup>
</s:View>
Regarding the device orientation, you should use:
trace(Stage.deviceOrientation);
trace(Stage.orientation);
They are read-only strings outputting information regarding the device's and the screen's orientation. You may manually set the stage's orientation:
Stage.setOrientation(StageOrientation.DEFAULT);
Regarding the image loading, you need an eventListener for Event.COMPLETE and you should also cast the content as Image:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void {
trace("Image loaded");
// Handle code here
// Use: (loader.content as Image)
});
loader.load(new URLRequest("images/1.jpg"));

rummy card placement on canvas

I am trying to place 5 cards overlapping 30% on one another. and trying to give a movement to it using mouse events . It should drop within the 5 cards only, not outside of that.
I have learned the drag and drop events and executed it, but i cannot place the card within the 5 cards .
Please somebody help me in this. Please Check the Below Code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="carcan();">
<mx:Script>
<![CDATA[
import mx.containers.Canvas;
import mx.controls.Image;
private var images:Array;
private var images1:Array;
private const IMAGE_COUNT:uint = 5;
private var img:Image;
private var img1:Image;
private var points:flash.geom.Point;
private var offset_x:int;
private var offset_y:int;
private var canal:Canvas;
private var doDrag:Boolean;
[Embed(source='cards/2C.png')]
private var Image0:Class;
[Embed(source='cards/2D.png')]
private var Image1:Class;
[Embed(source='cards/2H.png')]
private var Image2:Class;
[Embed(source='cards/2S.png')]
private var Image3:Class;
[Embed(source='cards/3C.png')]
private var Image4:Class;
public function carcan():void
{
canal = new Canvas();
canal.setStyle("backgroundColor","blue");
canal.x=100;
canal.y=50;
canal.width=500;
canal.height=400;
this.addChild(canal);
init();
}
public function init():void
{
images = new Array(IMAGE_COUNT);
for (var i:int = 0; i < IMAGE_COUNT; i++)
{
img= new Image();
img1= new Image();
images[i] = this["Image" + i];
trace(images[i]);
img.x=(i*30)+50;
img.source=images[i];
img.id="Image"+i;
canal.addChild(img);
img.addEventListener(MouseEvent.MOUSE_DOWN, md);
img.addEventListener(MouseEvent.MOUSE_MOVE, mm);
canal.addEventListener(MouseEvent.MOUSE_OUT,smu);
img.addEventListener(MouseEvent.MOUSE_UP, mu);
}
}
public function smu(event:MouseEvent):void
{
img.alpha=1;
img.stopDrag();
doDrag=false;
setCards();
}
public function mo(event:MouseEvent):void
{
if(doDrag==true)
{
img.addEventListener(MouseEvent.MOUSE_DOWN, md);
img.addEventListener(MouseEvent.MOUSE_UP, mu);
img.stopDrag();
img.alpha=1;
img.removeEventListener(MouseEvent.MOUSE_MOVE, mm);
}
else
{
img.addEventListener(MouseEvent.MOUSE_MOVE, mm);
}
}
public function md(event:MouseEvent):void
{
img = new Image();
doDrag=true;
canal.setChildIndex(Image(event.target),images.length-1);
img.addEventListener(MouseEvent.MOUSE_MOVE, mm);
}
public function mm(event:MouseEvent):void
{
if(doDrag==true)
{
points = new Point();
images = new Array(IMAGE_COUNT);
img = new Image();
img = Image(event.target);
points.x=event.target.x;
points.y=event.target.y;
points = localToGlobal(points);
img.x=points.x;
img.y=points.y;
img.alpha=0.7;
img.addEventListener(MouseEvent.MOUSE_UP, mu);
var boundar:flash.geom.Rectangle = new Rectangle(this.x, this.y, 250, 100);
}
}
public function mu(event:MouseEvent):void
{
img.alpha=1;
canal.stopDrag();
doDrag=false;
canal.stopDrag();
doDrag=false;
var current:Image = event.currentTarget as Image;
var num1:int = current.x;
if(num1 < 50){
canal.setChildIndex(current, images.length-5);
current.y=0;
setCards();
}
if(num1 > 50 && num1 < 80){
canal.setChildIndex(current, images.length-4);
current.y=0;
setCards();
}
if(num1 > 80 && num1 < 110){
canal.setChildIndex(current, images.length-3);
current.y=0;
setCards();
}
if(num1 > 110 && num1 < 140){
canal.setChildIndex(current, images.length-2);
current.y=0;
setCards();
}
if(num1 > 140 && num1 < 170){
canal.setChildIndex(current, images.length-2);
current.y=0;
setCards();
}
if(num1 > 170){
canal.setChildIndex(current, images.length-1);
current.y=0;
setCards();
}
}
private function setCards():void{
var b:int = 0;
var a:int;
var cardsArray:Array = canal.getChildren();
for(a = 0;a < cardsArray.length; a++)
{
canal.getChildAt(a).x = 50+b;
b=b+30;
canal.getChildAt(a).y=0;
}
}
]]>
</mx:Script>
</mx:Application>
PS: I am trying to replace the drag and drop events with mouse events and get the same functionality using mouse events. Please somebody help me in this.
Hope Below Code may help you: - You can use Drag and drop as per below code and create it in AS. I have created it in MXML which will give you some idea what you are looking for: -
<?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" minWidth="955" minHeight="600" xmlns:local="*">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.core.DragSource;
import mx.core.UIComponent;
import mx.events.DragEvent;
import mx.managers.DragManager;
private function doDragEnter(event:DragEvent):void
{
DragManager.acceptDragDrop(UIComponent(event.target));
}
private function doDragDrop(event:DragEvent):void
{
var img:RummyItemRenderer;
if (event.dragInitiator.parent == mainCanvas)
{
img = event.dragInitiator as RummyItemRenderer;
//mainCanvas.swapChildren(img, event.currentTarget as RummyItemRenderer);
var index:Number = mainCanvas.getChildIndex(event.currentTarget as RummyItemRenderer);
mainCanvas.removeChild(img);
mainCanvas.addChildAt(img,index);
setCardsPosition();
}
}
private function setCardsPosition():void{
var b:int = 0;
var a:int;
var cardsArray:Array = mainCanvas.getChildren();
for(a = 0;a < cardsArray.length; a++)
{
mainCanvas.getChildAt(a).x = 50+b;
b = b+30;
mainCanvas.getChildAt(a).y=20;
}
}
private function doDragStart(event:MouseEvent):void
{
var dragInitiator:RummyItemRenderer = event.currentTarget as RummyItemRenderer;
var dragSource:DragSource = new DragSource();
DragManager.doDrag(dragInitiator, dragSource, event);
}
]]>
</fx:Script>
<mx:Canvas id="mainCanvas" backgroundColor="#DDDDDD" width="400" height="200" x="50" y="50">
<local:RummyItemRenderer id="firstID" x="{mainCanvas.x}" y="20" width="200" height="80%" backgroundColor="#FF0000"
mouseDown="doDragStart(event)" dragEnter="doDragEnter(event)" dragDrop="doDragDrop(event)"
setImageSource="myImageURL"/>
<local:RummyItemRenderer id="secondID" x="{mainCanvas.x + 30}" y="20" width="200" height="80%" backgroundColor="#00FF00"
mouseDown="doDragStart(event)" dragEnter="doDragEnter(event)" dragDrop="doDragDrop(event)"
setImageSource="myImageURL"/>
<local:RummyItemRenderer id="thirdID" x="{mainCanvas.x + 60}" y="20" width="200" height="80%" backgroundColor="#0000FF"
mouseDown="doDragStart(event)" dragEnter="doDragEnter(event)" dragDrop="doDragDrop(event)"
setImageSource="myImageURL"/>
</mx:Canvas>
</s:Application>
RummyItemRenderer.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="100%" height="100%">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
[Bindable]
private var _setImageSource:String;
public function get setImageSource():String
{
return _setImageSource;
}
public function set setImageSource(sourceURL:String):void
{
_setImageSource = sourceURL;
}
]]>
</fx:Script>
<s:Image id="imageID" source="{_setImageSource}"/>
</mx:Canvas>

pass parameter in flex NativeProcess

I want to pass two parameter to nativeProcess.
While i am running exe file using windows command with parameter, it is working.
Command for window is "abc.exe a.txt b.txt"
How can I pass two parameters to the exe in that format using flex nativeProcess?
This is what I have so far:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="windowedapplication1_applicationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
private var process:NativeProcess;
protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void
{
if (NativeProcess.isSupported)
{
callExe();
}
else
{
textReceived.text = "NativeProcess not supported.";
}
}
public function callExe():void
{
var a_FilePath:String = File.applicationStorageDirectory.resolvePath("dist/a.txt").nativePath;
var b_FilePath:File = File.applicationStorageDirectory.resolvePath("dist/b.txt").nativePath;
if (Capabilities.os.toLowerCase().indexOf("win") > -1)
{
var file:File = File.applicationStorageDirectory.resolvePath("dist/abc.exe");
}
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
// i put the line below and it works in my case
nativeProcessStartupInfo.workingDirectory = File.applicationStorageDirectory.resolvePath();
nativeProcessStartupInfo.executable = file;
var args:Vector.<String> = new Vector.<String>();
args.push(a_FilePath);
args.push(b_FilePath);
nativeProcessStartupInfo.arguments = args;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(ProgressEvent.STANDARD_INPUT_PROGRESS, inputProgressListener);
process.addEventListener(ProgressEvent.PROGRESS, progressEvent);
process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, errorData);
}
public function inputProgressListener(event:ProgressEvent):void
{
textReceived.text += "Input Progress Event";
}
public function onOutputData(event:ProgressEvent):void
{
textReceived.text += "Output Event";
}
public function progressEvent(event:ProgressEvent):void
{
textReceived.text += "Progress Event";
}
public function errorData(event:ProgressEvent):void
{
textReceived.text += "Error Event";
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:TextInput id="textReceived" width="352" height="200"/>
</s:WindowedApplication>
I solved my puzzle by adding the line below in bold:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="windowedapplication1_applicationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
private var process:NativeProcess;
protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void
{
if (NativeProcess.isSupported)
{
callExe();
}
else
{
textReceived.text = "NativeProcess not supported.";
}
}
public function callExe():void
{
var a_FilePath:String = File.applicationStorageDirectory.resolvePath("dist/a.txt").nativePath;
var b_FilePath:File = File.applicationStorageDirectory.resolvePath("dist/b.txt").nativePath;
if (Capabilities.os.toLowerCase().indexOf("win") > -1)
{
var file:File = File.applicationStorageDirectory.resolvePath("dist/abc.exe");
}
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
// i put the line below and it works in my case
nativeProcessStartupInfo.workingDirectory = File.applicationStorageDirectory.resolvePath();
nativeProcessStartupInfo.executable = file;
var args:Vector.<String> = new Vector.<String>();
args.push(a_FilePath);
args.push(b_FilePath);
nativeProcessStartupInfo.arguments = args;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(ProgressEvent.STANDARD_INPUT_PROGRESS, inputProgressListener);
process.addEventListener(ProgressEvent.PROGRESS, progressEvent);
process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, errorData);
}
public function inputProgressListener(event:ProgressEvent):void
{
textReceived.text += "Input Progress Event";
}
public function onOutputData(event:ProgressEvent):void
{
textReceived.text += "Output Event";
}
public function progressEvent(event:ProgressEvent):void
{
textReceived.text += "Progress Event";
}
public function errorData(event:ProgressEvent):void
{
textReceived.text += "Error Event";
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:TextInput id="textReceived" width="352" height="200"/>
</s:WindowedApplication>

Creating table dynamically using AdvancedDatagrid

Number of rows & cols of table is taken from user in order to create table in one titlewindow.
After entering i open one more window consisting of table(AdvancedDatagrid) what happens is if generated table exceeds window width and height ,table comes out of window.
What to do to keep table inside the TitleWindow.
<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
title="Table Details"
initialize="tableDetailsWindow_initializeHandler(event)"
chromeColor="#5C809B" color="#D8E0E5"
creationComplete="tableDetailsWindow_creationCompleteHandler(event)"
width="506">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
import mx.core.FlexGlobals;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.managers.PopUpManager;
import spark.components.TextInput;
import spark.components.TileGroup;
[Bindable]
public var columnNameGroup :TileGroup;
[Bindable]
public var columnCount:Number;
[Bindable]
public var rowCount:Number;
var rowCollection : ArrayCollection = new ArrayCollection();
var columnNames :ArrayCollection = new ArrayCollection();
protected function tableDetailsWindow_initializeHandler(event:FlexEvent):void
{
dataGrid.rowCount= Number(FlexGlobals.topLevelApplication.insertTableConfigWindow.rowCount.text)+1;
}
protected function tableDetailsWindow_creationCompleteHandler(event:FlexEvent):void
{
columnNameGroup = FlexGlobals.topLevelApplication.insertTableConfigWindow.tileGroupOfColsInfo;
columnCount = Number(FlexGlobals.topLevelApplication.insertTableConfigWindow.columnCount.text);
rowCount = Number(FlexGlobals.topLevelApplication.insertTableConfigWindow.rowCount.text);
//Creation of Column Name collection
for(var i:Number= 0; i< columnCount; i++ ){
var textInputId :String ="textInput"+ (i+1);
var textInput :TextInput = columnNameGroup.getChildByName(textInputId) as TextInput;
columnNames.addItem(textInput.text);
}
//Creation of Rows collection
for(var j:Number= 0; j< rowCount; j++ ){
var obj:Object = new Object();
for each(var colName : * in columnNames){
obj.colName ="";
}
rowCollection.addItem(obj);
}
dataGrid.dataProvider = rowCollection;
var columns:Array = dataGrid.columns;
for(var k:Number= 0; k< columnNames.length; k++ ){
var adgColumn:AdvancedDataGridColumn = new AdvancedDataGridColumn();
adgColumn.dataField = columnNames.getItemAt(k) as String;
adgColumn.editable = true;
columns.push(adgColumn);
}
dataGrid.columns = columns;
}
]]>
</fx:Script>
<mx:AdvancedDataGrid id="dataGrid"
editable="true" verticalScrollPolicy="off"
sortableColumns="false"
x="0" y="0" />
</s:TitleWindow>
Did you try setting the width of your AdvancedDataGrid?
<mx:AdvancedDataGrid id="dataGrid"
width="506" <=== Set the width here
editable="true" verticalScrollPolicy="off"
sortableColumns="false"
x="0" y="0" />
Alternatively, you can set the width dynamically but then you need to listen to the resize event of your window.