AS3 Sprite Handler - actionscript-3

I want to use Object Handler for Sprite but any of the Handler not working for Sprite Please any one suggest me how can i Handle Sprite Component with Object Handler
<s:Application name="Spark_SpriteVisualElement_addChild_test"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
initialize="init();">
<fx:Script>
<![CDATA[
import mx.core.UIComponent;
private const spr1:Sprite = new Sprite();
private var bmd:BitmapData;// = new BitmapData();
private function init():void {
spr1.graphics.beginFill(0xFF0000, 0.5);
spr1.graphics.drawRect(10, 10, 100, 80);
spr1.graphics.endFill();
spr.addChild(spr1);
}
]]>
</fx:Script>
<s:SpriteVisualElement id="spr" />

Check out Object Handles.
What is it?
Actionscript 3 Library to enable user movement & resizing of components.

Below code may help you: -
private function init():void
{
spr1.graphics.beginFill(0xFF0000, 0.5);
spr1.graphics.drawRect(10, 10, 100, 80);
spr1.graphics.endFill();
spr.addChild(spr1);
spr1.addEventListener(MouseEvent.CLICK, onClickHandler);
}
private function onClickHandler(event:MouseEvent):void
{
trace("Click Perform")
}

Related

How to control an m4a file

I am playing m4a files that require that I use a NetStream object and want to control the audio with a SoundChannel object (because that is the only way I know to sync an HSlider control with an audio file). My problem is that I cannot connect the Sound Channel with the audio source. The event handler button1_clickHandler does not even regognize the existance of the SoundChannel object. Is there a way to control this type of audio file with a SoundChannel? If not, how can I set the position of the HSlider-- I've tried using HSlider.value, but that somehow gets overridden.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600" creationComplete="init()">
<mx:Script>
<![CDATA[
private var audioExample:AudioExample_M4A;
public function init():void{
audioExample = new AudioExample_M4A();
}
private function button1_clickHandler(event:MouseEvent):void{
if(audioExample.soundChannel){
audioExample.soundChannel.stop()
trace("Yes")
}else{
trace("No")
}
}
]]>
</mx:Script>
<mx:Button label="Play / Pause" click="button1_clickHandler(event)"/>
</mx:Application>
Here is the class file AudioExample_M4A.as:
package {
import flash.display.Sprite;
import flash.events.*;
import flash.media.SoundChannel;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class AudioExample_M4A extends Sprite {
public var soundChannel:SoundChannel= new SoundChannel();;
public var temp:String = new String()
public var audioURL:String = "badge.m4a";
private var connection:NetConnection;
public var stream:NetStream;
public function AudioExample_M4A() {
connection = new NetConnection();
connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
connection.connect(null);
}
private function netStatusHandler(event:NetStatusEvent):void {
switch (event.info.code) {
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetStream.Play.StreamNotFound":
break;
}
}
private function connectStream():void {
stream = new NetStream(connection);
stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
stream.client={onMetaData:function(obj:Object):void{
trace("metadata: duration=" + obj.duration);
}
}
soundChannel = stream.play(audioURL) as SoundChannel;
}
}}
You cannot control a NetStream object with a SoundChannel object. These are two completely different methods to playing media and, as far as I know, do not share a common base.
To allow for a slider to control the pointer position, you need to do the following:
Get the slider position as a percentage (slider.position * slider.minimum/slider.maximum in Spark, not sure about in MX)
Get the duration of the song. This is retrieved via NetStream.onMetaData
Call NetStream.seek() with an argument of slider percentage multiplied by duration (seek() expects the value in seconds). So NetStream.seek( duration * positionPercentage )

Embed Sound in CSS in flex

I am trying to use sound in flex. I got the output using urlrequest, as I have less sound files to use, and need not to load everytime i call it. So I tried to put that in css and use it, but I am getting an error : TypeError: Error #1007: Instantiation attempted on a non-constructor.
Below is my code
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Style>
draw
{
url:"Assets/Sound/Active.mp3";
}
</mx:Style>
<mx:Script>
<![CDATA[
import flash.media.Sound;
import flash.media.SoundTransform;
internal var sound:Sound;
internal var soundVolume:SoundTransform;
public function playSound():void
{
var SoundClass:Class;
try
{
SoundClass = StyleManager.getStyleDeclaration("draw").getStyle("url") as Class;
soundVolume = new SoundTransform(1, 0);
trace("sound : "+sound);
sound = new SoundClass() as Sound;
sound.play(0, 0, soundVolume);
}
catch(E:Error)
{
trace("E "+E);
}
}
]]>
</mx:Script>
<mx:Button click="playSound()" label="Discard"/>
</mx:Application>
draw {
url:Embed(source="Assets/Sound/Active.mp3");
}
Refer this

as3 How to create a DropDownList (no XML)

I'm a newbie in AS3 and I'm doing some simple UI. I want to create a dropdown list with a couple of options. I have read a lot of tutorials with hundreds of lines for making a dropdown list. Really? A hundred lines for a dropdown list? I just want to create a simple kind of HTML SELECT. If you know a tutorial that will also work.
I'm really sorry for this kind of question, but I really donĀ“t find any written in as3.
I have already checked the one that adobe is giving is its page adobe reference for DropDownList but that example is using XML.
Pure AS3 based Class:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import com.greensock.*;
import com.greensock.easing.*;
public class MouseOverMenu extends MovieClip {
public var _sMouseOver:MovieClip;
public var _sMenu:MovieClip;
private var _menuTimer:Timer;
private var _menuOpen:Boolean = false;
public function MouseOverMenu():void {
addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);
}
private function init(e:Event):void {
_sMouseOver.buttonMode = true;
_sMouseOver.addEventListener(MouseEvent.MOUSE_OVER, showMenu, false, 0, true);
_sMouseOver.addEventListener(MouseEvent.MOUSE_OUT, startClose, false, 0, true);
_sMouseOver.addEventListener(MouseEvent.MOUSE_OVER, cancelClose, false, 0, true);
_menuTimer = new Timer( 50 );
_menuTimer.addEventListener ( TimerEvent.TIMER, doCloseMenu );
_sMenu.visible = false;
_sMenu.alpha = 0;
_sMenu.addEventListener(MouseEvent.MOUSE_OUT, startClose, false, 0, true);
_sMenu.addEventListener(MouseEvent.MOUSE_OVER, cancelClose, false, 0, true);
}
private function showMenu(e:MouseEvent):void {
_menuOpen = true;
_sMenu.visible = true;
TweenLite.to(_sMenu, .5, {y:73, alpha:1});
}
private function startClose ( e:Event ):void {
//trace('startClose ' + e.target);
_menuTimer.start();
}
private function cancelClose ( e:Event ):void {
//trace('cancelClose ' + e.target);
_menuTimer.stop();
}
private function doCloseMenu ( e:Event ) {
closeMenu();
}
private function closeMenu ():void {
if ( _menuOpen ) {
TweenLite.to(_sMenu, .5, {y:50, alpha:0, onComplete: hideMenu});
}
_menuTimer.stop();
_menuOpen = false;
}
private function hideMenu():void {
_sMenu.visible = false;
}
}
}
I dont see an XML being used in the example mentioned by you, anyways this is a simple code for Dropdownlist in Flex which uses arrayCollection.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/03/07/using-the-dropdownlist-in-flex-gumbo/ -->
<s:Application name="Spark_DropDownList_test"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:BasicLayout />
</s:layout>
<s:DropDownList id="dropDownLst"
requireSelection="true"
horizontalCenter="0" top="20">
<s:dataProvider>
<s:ArrayList source="[The,quick,brown,fox,jumps,over,the,lazy,dog]" />
</s:dataProvider>
</s:DropDownList>
</s:Application>
you can do it by code if you don't want to use MXML:
yourDropDownInstance.dataProvider = new ArrayCollection(["The","quick",
"brown","fox",
"jumps","over",
"the","lazy","dog"]);

Adobe Flex: How to periodically poll HTTP service?

I have an embedded system that serves JSON results via a CGI process. I'm trying to setup a Flex app. to periodically poll the server once per second and update the GUI. I'm trying the approach below using a timer, but I only get the initial result, subsequent updates are not made. What could be going wrong?
<?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="application1_creationCompleteHandler(event)">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
<mx:HTTPService id="getPacketCounts" showBusyCursor="true" resultFormat="text"
url="http://10.1.10.28/cgi-bin/getpacketcounts"
requestTimeout="500"
result="getPacketCounts_resultHandler(event)"
fault="faultHandler(event)">
</mx:HTTPService>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private var timer:Timer = new Timer(1000, 0);
private var counter:int;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
timer.addEventListener(TimerEvent.TIMER, timerListener);
timer.start();
}
private function timerListener(evt:Event):void {
label.text = "get http://10.1.10.28/cgi-bin/getpacketcounts";
getPacketCounts.send();
}
protected function getPacketCounts_resultHandler(event:ResultEvent):void
{
label.text = event.result.toString().substr(0, 60);
}
protected function faultHandler(event:FaultEvent):void
{
Alert.show("The server returned error code " + event.statusCode + ".", event.fault.faultString);
}
]]>
</fx:Script>
<s:Label id="label" text="v1.0"/>
</s:Application>
I can't see anything glaringly wrong with your code though I suspect the problem lies with your Timer getting out of sync with your HTTPService. Your Timer fires every second but it might take longer for your HTTPService to return a result and the next tick of your Timer tramples over the previous getPacketCounts.send() request. I'm not 100% sure about this though.
If I were writing this app I'd set it up so the Timer fired once, reset the Timer, sent of the HTTPService request, then waiting for a response before restarting the Timer.
// Make the Timer run once.
private var timer:Timer = new Timer(1000, 1);
// ....
// Add listeners to the Timer and start it
protected function application1_creationCompleteHAndler(event:FlexEvent):void
{
timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerListener);
timer.start();
}
// Send the request
private function timerListener(e:TimerEvent):void
{
timer.reset();
// Your other stuff
}
protected function getPacketCounts_resultHandler(event:ResultEvent):void
{
timer.start()
// Your code
}
protected function faultHandler(event:FaultEvent):void
{
timer.start()
// Your code
}

Send data from popup to main application.

I'm not getting the answer I'm looking for.
I want to send the request data i get to the main application.
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" remove="titlewindow1_removeHandler(event)"
width="400" height="220" layout="absolute" title="USER LOGIN">
<mx:Metadata>
[Event(name="commEvent", type="flash.events.Event")]
</mx:Metadata>
<mx:Script>
<![CDATA[
import data.Data;
import mx.events.FlexEvent;
import mx.managers.PopUpManager;
[Bindable]
public var userID:String;
private function loginUser():void{
trace("btn");
var req:URLRequest = new URLRequest('http://localhost/CCN/userProcess.php');
var loader:URLLoader = new URLLoader();
req.method="POST";
var variables:URLVariables = new URLVariables();
variables.email= username.text;
variables.password= password.text;
variables.action= "login_user";
req.data=variables;
loader.addEventListener(Event.COMPLETE,onDataLoaded);
loader.load(req);
}
protected function loginButton_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
loginUser();
}
private function onDataLoaded(e:Event):void{
var xml:XML= new XML(e.target.data);
if(xml.status=="success"){
//SEND DATA TO MAIN APPLICATION ????
PopUpManager.removePopUp(this);
}else{
fail.visible=true;
username.text="";
password.text="";
username.setFocus();
}
}
protected function loginButton_keyDownHandler(ee:KeyboardEvent):void
{
// TODO Auto-generated method stub
if(ee.keyCode==13){
loginUser();
}
}
protected function titlewindow1_removeHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
}
]]>
</mx:Script>
<mx:TextInput id="username" x="141" y="31" width="199" text=""/>
<mx:TextInput keyDown="loginButton_keyDownHandler(event)" text="000" id="" x="141" y="84" width="199" displayAsPassword="true"/>
<mx:Button id="loginButton" x="275" y="133" label="LOGIN" click="loginButton_clickHandler(event)"/>
<mx:Label x="22" y="33" text="Email"/>
<mx:Label x="22" y="86" text="Password"/>
<mx:Label x="22" visible="false" y="135" id="fail" color="#FF0000" text="LOGIN FAILED"/>
</mx:TitleWindow>
here is the main application code
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
minWidth="955" minHeight="600" backgroundColor="#FFFFFF"
creationComplete="application1_creationCompleteHandler(event)" layout="absolute">
<mx:Script>
<![CDATA[
import mx.containers.TitleWindow;
import mx.core.IFlexDisplayObject;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.managers.PopUpManager;
//private var loginWindow:TitleWindow;
public var user:String;
private var login:Login
private function application1_creationCompleteHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
login = Login(
PopUpManager.createPopUp(this, Login, true));
PopUpManager.centerPopUp(login);
//login['loginButton'].addEventListener(MouseEvent.CLICK,onClose);
login.addEventListener(CloseEvent.CLOSE,oncc)
}
private function onClose(e:Event):void{
trace("Trace : "+login.userID);
}
private function
]]>
</mx:Script>
</mx:Application>
I would recommend solving this by adding a custom event, as your tag implies you may understand.
If not, here are the steps you would follow.
1) Create a new Event type (extend the Event class in actionscript - be sure to override clone())
2) Add an event listener for your new Event type in the parent application on the popup
3) cause the popup to dispatch your new Event type before it closes
4) Handle whatever it is you're looking for (userID?) in the event handler.
I would recommend attaching the userID to the actual event, so that the parent is not directly addressing login.userID. From a loose coupling standpoint, it's more correct. That said, if you don't wish to, you can simplify the solution by NOT attaching the userID. Loose coupling is a great goal, but if you only plan to use this relationship once, it's not incredibly necessary.
If you choose to go the tighter coupling route, then you only have to dispatch an event with a custom "type" instead of an extended Event.
If you need a lower level example (less description, more code) let me know, and I can help with that as well.
The example provided below is the slightly more complex version, where you extend an event to contain the data.
Event class::
package mycomponents
{
import flash.events.Event;
public class CustomEvent extends Event
{
public static const EVENT_TYPE_NAME:String = "myEventType"
public var mUserID:String = "";
public var mSuccess:Boolean = false;
public function CustomEvent(aType:String, aUserID:String, aSuccess:Boolean)
{
super(aType)
mUserID = aUserID;
mSuccess = aSuccess;
}
override public function clone():Event
{
var lEvent:CustomEvent = new CustomEvent(mUserID, mSuccess);
return lEvent;
}
}
}
In Popup::
private var loginSuccessful:Boolean = false;
private function onDataLoaded(e:Event):void{
var xml:XML= new XML(e.target.data);
if(xml.status=="success"){
userID = username.text;
loginSuccessful = true;
//SEND DATA TO MAIN APPLICATION
dispatchEvent(new CustomEvent(CustomEvent.EVENT_TYPE_NAME, userID, loginSuccessful );
PopUpManager.removePopUp(this);
}else{
fail.visible=true;
username.text="";
password.text="";
username.setFocus();
}
}
protected function titlewindow1_removeHandler(event:FlexEvent):void
{
if (!loginSuccessful)
dispatchEvent(new CustomEvent(CustomEvent.EVENT_TYPE_NAME," userID, loginSuccessful ));
}
And in the Main Application::
import mycomponents.CustomEvent;
private function application1_creationCompleteHandler(event:FlexEvent):void
{
//...your code
login.addEventListener(CustomEvent.EVENT_TYPE_NAME, handleLoginEvent);
}
private function handleLoginEvent(aEvent:CustomEvent)
{
//My example code dispatches an event with mSuccess = false if the login prompt closes
//without a successful login
//
//now do whatever you want with the information from the popup
//aEvent.mUserID gets you ID
//aEvent.mSuccess gets you success
}
Tossed that together in the middle of a break at work, so no promises will compile as-is.