Dispatching Custom Events Help

Hello Everyone,
I am just learning how to handle custom events, and after spending couple of days tring to understand the process, I am unable to get it going. What I am trying to do is to write a Two Button (component/swf). So when I need to utilize this component in other projects, I can simply load the the swf and be able to fire the buttons.
I have two button objects on the stage, and I would like these two button object to fire custom events when the parent component is loaded as swf in other projects. Perhaps, I am going all wrong about what I am tring to accomplish here, I would highly appreciate your help.
After some research, I concluded that I will need to employ Custom Event(s) going for my component. I spent hours on google and have not been able to get it working.
Here is my code:
============================
CustomEvent Class
============================
package com.custom.apps
    import flash.events.Event;
    public class CustomEvent extends Event
        public static const CUSTOM:String = "custom";
        public var arg:*;
        public function CustomEvent(type:String, customArg:*=null, bubbles:Boolean=false, cancelable:Boolean=false)
            super(type, bubbles, cancelable);
            this.arg = customArg;
        public override function clone():Event
            return new CustomEvent(type, arg, bubbles, cancelable);
        public override function toString():String
            return formatToString("CustomEvent", "type", "arg",    "bubbles", "cancelable", "eventPhase");
============================
DISPATCHING THE EVENTS
============================
import com.custom.apps.*;
btn.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(e:MouseEvent):void
    dispatchEvent(new Event(CustomEvent.CUSTOM, customHandler));
    //trace("FIRED");
function customHandler(e:CustomEvent):void
    trace(e.target);
    trace('hello');

Kalisto,
I appreciate your help. Do I have this right? So I can build a navigation component with two links:
LINK1 | LINK2
then I load this navigation component/swf into another project and when I click on either of the links, it will dispatch a CUSTOM EVENT and when the event is dispatched, lets say I have a  function (sayHello) listening for that particular event and when the CUSTOM EVENT is dispatched when one of the navigation component's link is clicked the (sayHello()) function would fire itself.
Can this be done? Am I on the right track?
I have been at it for couple of days now, I am able to dispatch the event but don't know how to have a function listen for the events. I would highly appreciate it if you can have look at my code.
Thanks a lot

Similar Messages

  • Dispatch custom event from itemClick handler

    hi,
    I'm trying to dispatch a custom event from my itemClick handler.
    So when I click on an item of my datagrid, I want to send a custom event.
    private function dataGridItemClickHandler( event:ListEvent): void
         dispatchEvent( new myEvent( myEvent.NEW, values[event.columnIndex]["name"]) );
    <mx:DataGrid dataProvider="{values}" itemClick="dataGridItemClickHandler(event)">
    </mx:DataGrid>
    but this code doesn't work.
    Can you help me
    thanks
    best regards

    Please see that you override the function clone() and return the new function.If that is correct.you can call the super() method to initialize your base class.
    If your custom event {myEvent} is in package say: CustomEvent,
    1)import package CustomEvent.myEvent
    2) keep in <mx:metadata>[Event(name="NEW", type="CustomEvent.myEvent")]</mx:metadata>.. name suggest  what type of event you want
    3)Create an itemclick listener and in dataGridItemClickHandler
    private function dataGridItemClickHandler( event:ListEvent): void
         dispatchEvent( new myEvent( ' NEW ', values[event.columnIndex]["name"]) );
    private funcation myEventListener(evt:myEvent):void
    //Put your logic
    4)Use this event by name NEW="myEventListener(event)"  this will behave as event type in the datagrid tag like click, hover and others.
    Hope this helps! Please excuse if anything is logically incorrect.Do point out.Thanks.

  • Dispatching Custom Event

    Hello everybody,
    Task: I want to enter a message in input text field and
    write it in the dynamic using a custom event dispatching.
    Solution: I have 2 textfields on the stage.
    One textfield is an input text field the other is a dynamic
    text field which will server just to display text.
    on the flash in the first frame I made this code:
    // mb is the instance name of the dynamic text field already
    placed on the stage
    var messageBoard:MsgBoard = new MsgBoard(mb);
    // u1 is the input text field placed on the stage
    var user1:UserInput = new UserInput(u1);
    Also I wrote 3 very simple classes.
    1. UserInput.as // input textfield class that listens to
    input and dispatches a custom event
    2. MsgEvnt.as // custom event class the instance of which is
    dispatched
    3. MsgBoard.as // class that listens to the new event and
    once it occurs adding event message to the textfield
    Problem: Somehow it doesn't work. I actually made it work by
    making a listener the same object that dispatches the event. But I
    want to understand why it doesn't works the way I showed above. I
    browsed a lot of forums and found that all the people use to listen
    by the same object that is dispatching. I think it's like talking
    with yourself isn't it?
    Thanks everybody who will reply and I hope it will help
    someone who will read!

    your event is dispatched within UserInput scope and MsgBoard
    is not within UserInput scope so it's not going to receive that
    event. ie, a UserInput instance is not accessible to MsgBoard.
    you may have a basic misunderstanding: events that are
    dispatched are not like radio signals that are transmitted and
    anyone with a listener (radio) can hear them.
    when you dispatch an event using actionscript, it is
    dispatched by an object (or sometimes by a class) and that event
    can only be detected by the dispatching object (or class).

  • How to dispatch custom events from an item renderer used for Datagrid Column

    Hi,
    I am using an Item Renderer for a Data Grid Column and in that mxml, I am dispatching a custom event with data.
    But the main mxml which has the DataGrid is not able to resolve the event. How can I solve this?
    Thanks

    Hi,
    This is the constructor for Event.
    public function Event(type:String, bubbles:Boolean  = false, cancelable:Boolean  = false)
    When you created your custom event after extending from Event, for the parent container receives the event, the bubbles property must be set to true.
    Please check if you have done so. That should solve the problem. Let me know if it doesn't.
    Nishad

  • Custom Event Issue

    Hope you flex geniuses can help me on this one....
    the issue: an action script custom event is being dispatched
    by one object but is not being "heard" by it's parent despite the
    fact that a) the child object uses the [event] declaration in it's
    class definition, b) the event is being correctly dispatched, and
    c) the parent object uses an addEventListener method to listen for
    the event.
    the layout:
    includes an application component (mxml) that has as it's
    only direct child an action script custom component called
    FloorPlan. On creationComplete the floor plan object instantiates
    an action script class called Booth as many times as is required
    (based on the number of booths that needs to be displayed on the
    floor plan) and then adds the instances to itself via addChild()
    method. The booth objects are based on Sprite class and so they
    have click events, etc. When one of the booth instances is clicked,
    the click event of the booth instance fires and the handler creates
    an instance of the ShowCompanyProfileEvent (action script class
    based on the Event class) and then dispatches it. The
    ShowCompanyProfileEvent event handler for now should just open an
    Alert box.
    I know the code works within the Booth class because when I
    register an event listener in the booth class itself and then click
    on a booth, the listener "hears" the dispatched event and opens the
    Alert box.
    The problem is that The floor plan instance has a registered
    event listener to listen for the dispatched custom event also but
    nothing happens when I click a booth instance (which like I said
    should dispatch the custom event). I deleted the addEventListener
    code in the booth class thinking that maybe it was catching it
    first but still it wouldn't work.
    Any ideas? I have reallysearched and searched to no avail. As
    I mentioned, I get no errors at all when I compile and run the
    code. I just don't get the expected results.

    LensterRAD, don't know if I got the hole idea but I guess you
    are listening to the ShowCompanyProfileEvent directly on the
    FloorPlan, something like:
    FloorPlan.addEventListener(ShowCompanyProfileEvent,
    someFunction);
    if this is the case, you'll probably need to add the BUBBLE
    parameter to the event, so it will follow the hole event
    propagation model.
    something like: dispatchEvent(ShowCompanyProfileEvent,
    true);

  • Can you send custom events from one form to another?

    I have a compli
    cated application, where I about hundred inp
    uts organized in several input forms. Some of the forms
    require data which has been input in other forms. I have tried to
    dispatch custom events from one form to another, but it dispatches the
    whole form and I only need one or two items.
    Ha anybody else come across such a problem?
    Svend

    One way is to share data in a static singleton

  • Dispatching an event from a command

    Hi,
    In one for my commands in the Cairngorm based application I'm working on I need to dispatch a event to amend the view. In my command I'm amending some value objects in a ArrayCollection, which is the data source for a List component in my view. Once I completed my changes to these value objects I'd like to dispatch a event to resort the ArrayCollection and update my view to the new order.
    What is the best approach for dispatching an event in the command?
    Thanks
    Stephen

    Great question - I'm currently sorting out how to do this myself.  I'm new to Cairngorm but have a decent amount of experience with Flex.  Here are my thoughts:
    Cairngorm promotes decoupling of the data model and front controller/commands from the view - which is appropriate for an MVC framework. Data binding supports this seperation (to an extent) and keeps the view up to date with the model in 'real time'.  Data binding does not however provide an intuitive mechanism for reacting to cairngorm event results.  So here a few solutions I've been tossing around:
    1.  Rely on Built in Flex events such as the datagrid's dataChange event to trigger a reaction.
    2.  Create view state variables in the model that, when changed through the front controller / commands, dispatch custom events from within their VO's / setters / ect.
    3.  Dispatch custom events directly from front controller / commands.
    4.  Create custom (or override existing) item renderers that self-transition / tween when changed as a result of data binding.
    I'm sure there are other ways to do what we want, but I'm out of ideas.  Which approach to take very well depends on how strongly you'd like to adhere to the MVC concept.  Commands that dispatch generic events as their messages may or may not be acceptable to you - but they provide a straitforward way to trigger view related reactions without relying on data binding events.  I'd be interested to know if Cairngorm 3 will address this challenge...
    Let me know what you decide on if and when you make a choice!

  • Dispatching an event.

    Hey all, I can't seem to dispatch an event. Am I just missing something?
    I have a  class called Activities that extends the MovieClip class and it imports the following classes:
    import flash.display.MovieClip;
    import flash.events.EventDispatcher;
    import flash.events.Event;
    import flash.events.MouseEvent;
    in the constructor I have a listener listening for a rollover of various Movie clips on the stage.  (this event is working)
    this.addEventListener(MouseEvent.ROLL_OVER, sendInfo);
    I want to dispatch a custom event (in this case just to my document class) from the sendInfo() function when the roll over happens. like so:
    private function sendInfo(event:MouseEvent):void
         dispatchEvent(new Event("MyEvent"));
         //other stuff in the function
    in my document class named Main I am importing the follwoing classes
    import com.activities.Activities;
    import flash.display.MovieClip;
    import flash.events.Event;
    in the constructor I have the following listener
    addEventListener("MyEvent", eventPassed);
    with the following function:
    function eventPassed(event:Event):void
         trace("works");
    It seems to me that this should work, but when I roll over any of the Movie clips on the stage, it registers I rolled over it (i verified with a trace statement in the sendInfo() function), but does not seem to dispatch the event as the trace statement int he document class is not being called.
    I used this as reference for setting up my custom disptach.
    http://www.learningactionscript3.com/2007/11/20/dispatching-custom-events/
    thanks.

    Hey
    your problem is right here:
    addEventListener("MyEvent", eventPassed);
    your adding the event just right only your event by default is not a bubbling event so when your trying to listen to it globaly it wouldn't work you would need to actually ask for the event directly :
    yourClip.addEventListener("MyEvent", eventPassed);
    now if you want it to bubble (you should avoid it as much as you can to cut down on processing when its not needed)
    you can send a second param to the event diapatchment:
    dispatchEvent(new Event("MyEvent",true));
    so flash knows it should bubble the event all the way up.
    by the way talking about events check out The EventController i don't want to dig to deep into it becouse its off topic but you might find it useful
    Best
    Ben Fhala@

  • Eventhandlers of children of application can not receive custom event dispatched by application

    Hello dear Adobe community,
    hope you can help me with this issue.
    When the application dispatches a custom event, the child uicomponent can only receive the event by using Application.application.addEventListener or systemManager.addEventListener. Simply adding a listener, without application or systemmanager, does not allow the event to be received by the child component.
    I want to be able to use the addEventListener and removeEventListener without SystemManager or Application.application, or could you provide a better workaround? How can I use the addEventListener, do I need to overwrite EventDispatcher, which I wouldnt like to do?
    Just to clarifiy, if i remove the systemManager in front of addEventListener(CustomEventOne.EventOne,sysManHandleCE,false) it will not add it and will not fire. 
    The code below is an example for this problem that the event is not getting fired in the right moment. The mainapplication got only a button with the customEventOne that gets dispatched.
    public
    class MyCanvas extends Canvas{
    public function MyCanvas()
    super();
    width=300;
    height=300;
    addEventListener(FlexEvent.CREATION_COMPLETE,handleCC,false,0,true);
    private function handleCC(event:FlexEvent):void
    removeEventListener(FlexEvent.CREATION_COMPLETE,handleCC);
    addEventListener(CustomEventOne.EventOne,handleCE,false,0,true);
    addEventListener(Event.REMOVED_FROM_STAGE,handleEvt,false,0,true);
    systemManager.addeventListener(CustomEventOne.eventOne,sysManHandleCE,false,0,true);
    private function handleEvt(event:Event):void
    trace("In removed from stage handler");
    systemManager.removeEventListener(CustomEventOne.EventOne,sysManHandleCE);
    trace(hasEventListener(FlexEvent.CREATION_COMPLETE));
    trace(hasEventListener(CustomEventOne.EventOne));
    trace(hasEventListener(Event.REMOVED_FROM_STAGE));
    private function handleCE(event:CustomEventOne):void
    trace("I got it");
    private function sysManHandleCE(event:CustomEventOne):void
    trace("I got it");
    public class CustomEventOne extends Event
    public static const EventOne:String = "EventOne";
    public function CustomEventOne(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
    super(type, bubbles, cancelable);
    override public functionclone():Event
    return newCustomEventOne(type,bubbles,cancelable);
    Thank you in advance,
    Michael

    I think you need to look at event propogation. The object that dispatches an event will be sitting on the display tree. The event propagates up the tree to the roots. Your canvas should be attached to the application, but even then it sits lower in the tree branches than the event dispatcher, so it won't see the event being dispatched because the event is not propagated to the children of the object that dispatches it but to the parent of the object that dispatches it.
    So, your canvas is a child of the application, but dispatching the event from the application means that the canvas doesn't see it because events are notified up the tree using the parent link, not the child links.
    You may wish to investigate how the display list and event propagation works and then the MVC pattern.
    Paul

  • Need help with custom event from Main class to an unrelated class.

    Hey guys,
    I'm new to Flash and not great with OOP.  I've made it pretty far with google and lurking, but I've been pulling my hair out on this problem for a day and everything I try throws an error or simply doesn't hit the listener.
    I'm trying to get my Main class to send a custom event to an unrelated class called BigIcon.  The rest of the code works fine, it's just the addEventListener and dispatchEvent that isn't working.
    I've put in the relevant code in below.  Let me know if anything else is needed to troubleshoot.  Thank you!
    Main.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        public class Main extends MovieClip
            var iconLayer_mc:MovieClip = new MovieClip();
            public function Main()
                Spin_btn.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler);
                addChildAt(iconLayer_mc,0);
                placeIcons();
            function placeIcons():void
                var i:int;
                var j:int;
                for (i = 0; i < 4; i++)
                    for (j = 0; j < 5; j++)
                        //iconString_array has the names of illustrator objects that have been converted to MovieClips and are in the library.
                        var placedIcon_mc:BigIcon = new BigIcon(iconString_array[i][j],i,j);
                        iconLayer_mc.addChild(placedIcon_mc);
            function fl_MouseClickHandler(event:MouseEvent):void
                dispatchEvent(new Event("twitchupEvent",true));
    BigIcon.as
    package
        import flash.display.MovieClip;
        import flash.events.Event;
        import flash.utils.getDefinitionByName;
        public class BigIcon extends MovieClip
            private var iconImage_str:String;
            private var iconRow_int:int;
            private var iconColumn_int:int;
            public function BigIcon(iconImage_arg:String, iconRow_arg:int, iconColumn_arg:int)
                iconImage_str = iconImage_arg;
                iconRow_int = iconRow_arg;
                iconColumn_int = iconColumn_arg;
                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
            function Setup(e:Event)
                this.y = iconRow_int;
                this.x = iconColumn_int;
                var ClassReference:Class = getDefinitionByName(iconImage_str) as Class;
                var thisIcon_mc:MovieClip = new ClassReference;
                this.addChild(thisIcon_mc);
                addEventListener("twitchupEvent", twitchUp);
            function twitchUp(e:Event)
                this.y +=  10;

    Ned Murphy wrote:
    You should be getting an error for the Main.as class due to missing a line to import the Event class...
    import flash.events.Event;
    My apologies, I should attempt to compile my example code before I ask for help...
    Alright, this compiles, gives me no errors, shows my 'book' and 'flowers' icons perfectly when ran, and prints 'addEventListener' to the output window as expected.  I get no errors when I press the button, 'dispatchEvent' is output (good), but the 'twitchUp' function is never called and 'EventTriggered' is never output. 
    How do I get the 'twitchUp' event to trigger?
    Main.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        import flash.events.*;
        public class Main extends MovieClip
            var iconLayer_mc:MovieClip = new MovieClip();
            var iconString_array:Array = new Array(2);
            public function Main()
                Spin_btn.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler);
                addChildAt(iconLayer_mc,0);
                buildStringArray();
                placeIcons();
            function buildStringArray():void
                var i:int;
                var j:int;
                for (i = 0; i < 2; i++)
                    iconString_array[i] = new Array(3);
                    for (j = 0; j < 3; j++)
                        if (Math.random() > .5)
                            //'flowers' is the name of an illustrator object that has been converted to a MovieClip and is in the library
                            iconString_array[i][j] = "flowers";
                        else
                            //'book' is the name of an illustrator object that has been converted to a MovieClip and is in the library
                            iconString_array[i][j] = "book";
            function placeIcons():void
                var i:int;
                var j:int;
                for (i = 0; i < 2; i++)
                    for (j = 0; j < 3; j++)
                        //iconString_array has the names of illustrator objects that have been converted to MovieClips and are in the library.
                        var placedIcon_mc:BigIcon = new BigIcon(iconString_array[i][j],i*50,j*50);
                        iconLayer_mc.addChild(placedIcon_mc);
            function fl_MouseClickHandler(event:MouseEvent):void
                dispatchEvent(new Event("twitchupEvent",true));
                trace("dispatchEvent");
    BigIcon.as
    package
        import flash.display.MovieClip;
        import flash.events.*;
        import flash.utils.getDefinitionByName;
        public class BigIcon extends MovieClip
            private var iconImage_str:String;
            private var iconRow_int:int;
            private var iconColumn_int:int;
            public function BigIcon(iconImage_arg:String, iconRow_arg:int, iconColumn_arg:int)
                iconImage_str = iconImage_arg;
                iconRow_int = iconRow_arg;
                iconColumn_int = iconColumn_arg;
                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
            function Setup(e:Event)
                this.y = iconRow_int;
                this.x = iconColumn_int;
                var ClassReference:Class = getDefinitionByName(iconImage_str) as Class;
                var thisIcon_mc:MovieClip = new ClassReference;
                this.addChild(thisIcon_mc);
                addEventListener("twitchupEvent", twitchUp);
                trace("addEventListener");
            function twitchUp(e:Event)
                this.y +=  10;
                trace("EventTriggered");
    Output:
    [SWF] Untitled-1.swf - 40457 bytes after decompression
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    dispatchEvent
    [UnloadSWF] Untitled-1.swf
    Test Movie terminated.

  • Please Help me with my Custom Event

    I am new in java, please help me about my custom event
    I have a simple source code about custom event but it doesn't work like I want. This code generate result :
    start
    end
    but I want result :
    start
    my custom event (from aaa method)
    end
    Thank you
    package TestBean;
    class MyEvent extends java.util.EventObject {
    public MyEvent(Object source) {
    super(source);
    interface MyEventListener extends java.util.EventListener {
    public void myEventOccurred(MyEvent evt);
    class MyClass {
    protected javax.swing.event.EventListenerList listenerList =
    new javax.swing.event.EventListenerList();
    public void addMyEventListener(MyEventListener listener) {
    listenerList.add(MyEventListener.class, listener);
    public void removeMyEventListener(MyEventListener listener) {
    listenerList.remove(MyEventListener.class, listener);
    protected void fireMyEvent(MyEvent evt) {
    Object[] listeners = listenerList.getListenerList();
    for (int i=0; i<listeners.length; i+=2) {
    if (listeners==MyEventListener.class) {
    ((MyEventListener)listeners[i+1]).myEventOccurred(evt);
    public class BeanFrame extends javax.swing.JFrame {
    public BeanFrame() {
    initComponents();
    MyClass c = new MyClass();
    System.out.println("start");
    c.addMyEventListener(new MyEventListener()
    public void myEventOccurred(MyEvent evt)
    aaa(evt);
    System.out.println("end");
    private void aaa(MyEvent evt) {                    
    System.out.println("my custom event");
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 400, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 300, Short.MAX_VALUE)
    pack();
    }// </editor-fold>
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new BeanFrame().setVisible(true);

    package TestBean;
    class MyEvent extends java.util.EventObject {
        public MyEvent(Object source) {
               super(source);
    interface MyEventListener extends java.util.EventListener {
        public void myEventOccurred(MyEvent evt);
    class MyClass {
        protected javax.swing.event.EventListenerList listenerList =
        new javax.swing.event.EventListenerList();
        public void addMyEventListener(MyEventListener listener) {
              listenerList.add(MyEventListener.class, listener);
        public void removeMyEventListener(MyEventListener listener) {
              listenerList.remove(MyEventListener.class, listener);
        protected void fireMyEvent(MyEvent evt) {
             Object[] listeners = listenerList.getListenerList();
             for (int i=0; i<listeners.length; i+=2) {
                    if (listeners==MyEventListener.class) {
                          ((MyEventListener)listeners[i+1]).myEventOccurred(evt);
    public class BeanFrame extends javax.swing.JFrame {
          public BeanFrame() {
                initComponents();
                MyClass c = new MyClass();
                System.out.println("start");
                c.addMyEventListener(new MyEventListener(){
                                  public void myEventOccurred(MyEvent evt){
                                              aaa(evt);
                System.out.println("end");
          private void aaa(MyEvent evt) {
                System.out.println("my custom event");
         // ><editor-fold defaultstate="collapsed" desc=" Generated Code ">
         private void initComponents() {
               setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
           javax.swing.GroupLayout layout = new 
           javax.swing.GroupLayout(getContentPane());
           getContentPane().setLayout(layout);
           layout.setHorizontalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGap(0, 400, Short.MAX_VALUE)
           layout.setVerticalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 300, Short.MAX_VALUE)
          pack();
    }// </editor-fold>
    public static void main(String args[]) {
             java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                      new BeanFrame().setVisible(true);
    }just enclosed it with the code tags.

  • Dispatching & listening for custom events from custom component [Flex 4.1]

    I'm giving this a try for the first time and I'm not sure I have the recipe correct!
    I have a custom component - it contains a data grid where I want to double click a row and dispatch an event that a row has been chosen.
    I created a custom event
    package oss
        import flash.events.Event;
        public class PersonChosenEvent extends Event
            public function PersonChosenEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
                super(type, bubbles, cancelable);
            // Define static constant.
            public static const PERSON_CHOSEN:String = "personChosen";
            // Define a public variable to hold the state of the enable property.
            public var isEnabled:Boolean;
            // Override the inherited clone() method.
            override public function clone():Event {
                return new PersonChosenEvent(type);
    Then I try to dispatch the event within the component when the datagrid is doubleclicked:
    import oss.PersonChosenEvent
    dispatchEvent(new PersonChosenEvent(PersonChosenEvent.PERSON_CHOSEN, true, false));
    And in the parent application containing the component I do on creationComplete
    addEventListener(PersonChosenEvent.PERSON_CHOSEN,addPersonToList);
    The event does not seem to fire though. And if I try to evaluate the "new PersonChosenEvent(..." code it tells me "no such variable".
    What am I doing wrong?
    (It was so easy in VisualAge for Java, what have we done in the last 10 years?? )
    Martin

    I've done this kind of thing routinely, when I want to add information to the event.  I never code the "clone" method at all.
    Be sure that you are listening to the event on a parent of the dispatching component.
    You can also have the dispatching component listen for the event too, and use trace() to get a debug message.
    I doubt if it has anything to to with "bubbles" since the default is true.
    Sample code
    In a child (BorderContainer)
    dispatchEvent(new ActivationEvent(ActivationEvent.CREATION_COMPLETE,null,window));
    In the container parent (BorderContainer)
    activation.addEventListener(ActivationEvent.CREATION_COMPLETE,activationEvent);
    package components.events
        import components.containers.SemanticWindow;
        import components.triples.SemanticActivation;
        import flash.events.Event;
        public class ActivationEvent extends Event
            public static const LOADED:String = "ActivationEvent: loaded";
            public static const CREATION_COMPLETE:String = "ActivationEvent: creation complete";
            public static const RELOADED:String = "ActivationEvent: reloaded";
            public static const LEFT_SIDE:String = "ActivationEvent: left side";
            public static const RIGHT_SIDE:String = "ActivationEvent: right side";
            private var _activation:SemanticActivation;
            private var _window:SemanticWindow;
            public function ActivationEvent(type:String, activation:SemanticActivation, window:SemanticWindow)
                super(type);
                _activation = activation;
                _window = window
            public function get activation():SemanticActivation {
                return _activation;
            public function get window():SemanticWindow{
                return _window;

  • Help with dispatching JTable event to underlying components in a cell.

    Hello..
    I have a JTable in which i show a panel with clickable labels.. I found that jTable by default doesnt dispatch or allow mouseevents to be caught by underlying elements..
    i need help with dispatching an event from jTable to a label on a panel in a jTable cell.. below is the code i have come up with after finding help with some websites. but i couldnt not get it right.. my dispatched event seems to go back to the jtable itself ..
    any help or suggestion is appreciated..
    Thanks
    'Harish.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.table.*;
    * @author  harish
    public class tableDemo extends javax.swing.JFrame {
        JTable jTable1;
        testpane dummyPane;
        /** Creates new form tableDemo */
        public tableDemo() {
            initComponents();
            //table settings
            String[] columnNames = {"Task", "Action"," "};
            Object[][] data = { };
            DefaultTableModel model = new DefaultTableModel(data, columnNames) {
              // This method returns the Class object of the first
              // cell in specified column in the table model.
            public Class getColumnClass(int mColIndex) {
                int rowIndex = 0;
                Object o = getValueAt(rowIndex, mColIndex);
                if (o == null)
                    return Object.class;
                } else
                    return o.getClass();
            jTable1 = new javax.swing.JTable(model);
            jTable1.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e){
                  System.out.println("Clicked");
                  handleTableMouseEvents(e);
                 //invokeExternalApp("http://www.pixagogo.com");
              public void mouseEntered(MouseEvent e){
                  System.out.println("Entered");
                  //handleTableMouseEvents(e);
              public void mouseExited(MouseEvent e){
                  System.out.println("Exited");
                  //handleTableMouseEvents(e);
            jTable1.setRowHeight(100);
            jTable1.getTableHeader().setReorderingAllowed(false);
            jTable1.setBackground(new java.awt.Color(255, 255, 255));
            jTable1.setGridColor(new Color(250,250,250));
            jTable1.setShowGrid(true);
            jTable1.setShowVerticalLines(true);
            jTable1.setShowHorizontalLines(false);
            jTable1.setFont(new Font("Arial",0,11));
            jTable1.setMaximumSize(new java.awt.Dimension(32767, 32767));
            jTable1.setMinimumSize(new java.awt.Dimension(630, 255));
            jTable1.setPreferredSize(null);
            jTable1.setBackground(new Color(255,255,255));
            int vColIndex=0;
            TableColumn col = jTable1.getColumnModel().getColumn(vColIndex);
            int width = 100;
            col.setPreferredWidth(width);
            //add item to 2nd cell       
            Vector vec = new Vector();
            vec.addElement(null);
            dummyPane = new testpane();
            vec.addElement(dummyPane);
            ((DefaultTableModel)jTable1.getModel()).addRow(vec);
            jTable1.repaint();
            this.getContentPane().add(jTable1);
            jTable1.getColumn("Action").setCellRenderer(
              new MultiRenderer());
        protected void handleTableMouseEvents(MouseEvent e){
            TableColumnModel columnModel = jTable1.getColumnModel();
            int column = columnModel.getColumnIndexAtX(e.getX());
            int row    = e.getY() / jTable1.getRowHeight();
            testpane contentPane = (testpane)(jTable1.getModel().getValueAt(row, column));
            // get the mouse click point relative to the content pane
            Point containerPoint = SwingUtilities.convertPoint(jTable1, e.getPoint(),contentPane);
            if (column==1 && row==0)
            // so the user clicked on the cell that we are bothered about.         
            MouseEvent ev1 = (MouseEvent)SwingUtilities.convertMouseEvent(jTable1, e, contentPane);
            //once clicked on the cell.. we dispatch event to the object in that cell
         jTable1.dispatchEvent(ev1);
        private void initComponents() {
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-528)/2, (screenSize.height-423)/2, 528, 423);
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new tableDemo().show();
        // Variables declaration - do not modify
        // End of variables declaration
        class testpane extends JPanel{
            public testpane(){
            GridBagConstraints gridBagConstraints;
            JPanel testpane = new JPanel(new GridBagLayout());
            testpane.setBackground(Color.CYAN);
            JLabel lblTest = new JLabel("test");
            lblTest.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e){
                  System.out.println("panelClicked");
              public void mouseEntered(MouseEvent e){
                  System.out.println("panelEntered");
              public void mouseExited(MouseEvent e){
                  System.out.println("panelExited");
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
            testpane.add(lblTest,gridBagConstraints);
            this.add(testpane);
    class MultiRenderer extends DefaultTableCellRenderer {
      JCheckBox checkBox = new JCheckBox();
      public Component getTableCellRendererComponent(
                         JTable table, Object value,
                         boolean isSelected, boolean hasFocus,
                         int row, int column) {
        if (value instanceof Boolean) {                    // Boolean
          checkBox.setSelected(((Boolean)value).booleanValue());
          checkBox.setHorizontalAlignment(JLabel.CENTER);
          return checkBox;
        String str = (value == null) ? "" : value.toString();
        return super.getTableCellRendererComponent(
             table,str,isSelected,hasFocus,row,column);
        return (testpane)value;
    class MultiEditor implements TableCellEditor {
      public MultiEditor() {
      public boolean isCellEditable(EventObject anEvent) {return false;}
      public boolean stopCellEditing() {return true;}
      public Object getCellEditorValue() {return null;} 
      public void cancelCellEditing() {}
      public boolean shouldSelectCell(EventObject anEvent) {return false;}
      public Component getTableCellEditorComponent(JTable table, Object value,
                  boolean isSelected, int row, int column) {
        if (value instanceof testpane) {                       // ComboString
          System.out.println("yes instance");
        return null;
      public void addCellEditorListener(javax.swing.event.CellEditorListener l) {
      public void removeCellEditorListener(javax.swing.event.CellEditorListener l) {
    }

    any help on this.. anybody. ?

  • Trying to make up a Modal Dialog with customized event dispatcher

    Hello everyone.
    I try to make up a ModalDialog class with customized event dispatcher in order to wait an invoker.
    But it fails :-(
    import javafx.event.ActionEvent;
    import javafx.event.Event;
    import javafx.event.EventDispatchChain;
    import javafx.event.EventHandler;
    import javafx.event.EventTarget;
    import javafx.event.EventType;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.HBox;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    import javafx.stage.StageStyle;
    import javafx.stage.Window;
    import javafx.stage.WindowEvent;
    import com.sun.javafx.stage.WindowEventDispatcher;
    import java.util.ArrayList;
    public class ModalDialog extends Stage {
      ArrayList<Button> buttons;
      int rc;
      Stage stage;
      Event event;
      EventDispatchChain tail;
      public ModalDialog( Window owner, String title ){
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        initStyle( StageStyle.UTILITY );
        setTitle( title );
        stage = this;
      public void setContents( Group group, ArrayList<Button> buttons ){
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root);
        setScene(scene);
        root.setCenter( group );
        this.buttons = buttons;
        HBox buttonPane = new HBox();
        buttonPane.setSpacing(10);
        for( int i=0 ; i<buttons.size() ; i++ ){
          buttons.get(i).setOnAction( actionHandler );
        buttonPane.getChildren().setAll( buttons );
        root.setBottom( buttonPane );
      public int show( double screenX, double screenY ){
        setX( screenX ); setY( screenY );
        show();
        MyWindowEventDispatcher dispatcher =  new MyWindowEventDispatcher( stage );
        setEventDispatcher( dispatcher );
        while(true){
          event = dispatcher.dispatchEvent( event, tail );
          EventType<? extends Event> type = event.getEventType();
          if( type==WindowEvent.WINDOW_HIDDEN ){
            break;
        return( rc );
      EventHandler<ActionEvent> actionHandler = new EventHandler<ActionEvent>() {
        public void handle( ActionEvent e ){
          EventTarget src = e.getTarget();
          rc = buttons.indexOf( src );
          stage.hide();
      class MyWindowEventDispatcher extends WindowEventDispatcher {
        public MyWindowEventDispatcher( Window window ){
          super( window );
        public Event dispatchEvent( Event event, EventDispatchChain tail) {
          ModalDialog.this.event = dispatchCapturingEvent( event );
          ModalDialog.this.tail = tail;
          return( event );
    }A sample code to invoke ModalDialog
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.stage.Stage;
    import javafx.stage.WindowEvent;
    public class WindowEvent06 extends Application {
      Stage mainStage;
      public void start(Stage stage) throws Exception {
        Group root = new Group();
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("WindowEvent06");
        mainStage = stage;
        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
          public void handle(WindowEvent e){
            ModalDialog dialog = new ModalDialog( mainStage, "Question" );
            Button yes = new Button( "Yes" );
            Button no  = new Button( "No" );
            ArrayList<Button> buttons = new ArrayList<>();
            buttons.add(yes); buttons.add(no);
            Label msg = new Label( "Really Exit ?" );
            Group groupInDialog = new Group();
            groupInDialog.getChildren().add( msg );
            dialog.setContents( groupInDialog, buttons );
            int ans = dialog.show( 300, 300 );
            System.out.println("returned from a modal dialog");
            if( ans == 1 ){
              e.consume(); // this blocks window closing
        stage.show();
      public static void main(String[] args) {
        launch(args);
    }

    Hi,
    The logic what you follows is some what in the right direction but need to have some changes.
    What I would say is, first consume the windowClose event. Then open the dialog box and close the parent accordingly.
    So after refactoring your code.
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.HBox;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    import javafx.stage.StageStyle;
    public class ModalDialog extends Stage {
         Stage owner;
         Stage stage;
         BorderPane root;
      public ModalDialog( Stage owner, String title){
        root = new BorderPane();
        stage = this;
        this.owner = owner;
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        initStyle( StageStyle.UTILITY );
        setTitle( title );
        setContents();
      public void setContents(){
        Scene scene = new Scene(root,150,150);
        setScene(scene);
        Group groupInDialog = new Group();
        groupInDialog.getChildren().add( new Label("Really Exit ?") );
        root.setCenter( groupInDialog );
        Button yes = new Button( "Yes" );
        yes.setOnAction(new EventHandler<ActionEvent>() {
              @Override
              public void handle(ActionEvent paramT) {
                   stage.close(); // Closing the pop up.
                   owner.close(); // Closing the parent stage also.
        Button no  = new Button( "No" );
        no.setOnAction(new EventHandler<ActionEvent>() {
              @Override
              public void handle(ActionEvent paramT) {
                   stage.close(); // Closing the pop up only
        HBox buttonPane = new HBox();
        buttonPane.setSpacing(10);
        buttonPane.getChildren().addAll(yes,no);
        root.setBottom(buttonPane);
        stage.show();
    }And the main class to check this implementation is
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    import javafx.stage.WindowEvent;
    public class WindowEvent06 extends Application {
      public void start(final Stage stage) throws Exception {
        Group root = new Group();
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("WindowEvent06");
        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
          public void handle(final WindowEvent e){
             e.consume(); // Consuming the event by default.
             new ModalDialog( stage, "Question");
        stage.show();
      public static void main(String[] args) {
        launch(args);
    }I hope the above code will give you some idea what i mean. :)
    Happy Coding !!
    Regards,
    Sai Pradeep Dandem.
    Edited by: Sai Pradeep Dandem on Jan 20, 2012 4:03 AM

  • Help with my custom event

    Hi all!
    I've extended JTextField to add some custom features. They can add my custom event called ValueChangedListener which listens for change in my textfields. Theese changes is registered in my JFrame holding the textfields so I can determine whether or not to save data to file on exit.
    My question is this:
    Can I listen to my custom events in a global way in my JFrame? Instead of adding the listener to each and every custom textfield (JFlexTextField) I would like to add ONE listener in my JFrame by calling MyJFrame.addValueChangedListener(ValueChangedEvent vce). (The method addValueChangedListener is located in my custom textfields).
    Thanks in advance.

    You need some kind of glue between the object that creates the message and the listeners. When the events are generated by your textfields, then those textfields needs at least one "address" to send the events to. Obviously, if the listener list is stored in the JFrame, your textfields will have difficulties using it.
    What you can do, which might help if you want to add several listeners to all the textfields, is:
    - Add only the JFrame as a listener to the textfields
    - Other listeners registers themselves with the JFrame
    - The JFrame keeps track of all the other listeners,
    - The 'valueChanged' method in the JFrame you forward the event to all the other listeners.
    You still have to call addValueChangedListener once for every textfield, though.
    You can also send a reference to the JFrame to the constructor for the textfields, and do the addValueChangedListener call in that constructor.

Maybe you are looking for

  • Help itunes wont sync songs to ipod

    im trying to put some songs on an ipod shuffle but it just doesnt seem to sync songs the green light stays on all the time when i sync its ment to be orange and flashing each time i remove it and try see if songs are on its empty whats going on can a

  • TS1398 Do I need anti-viral software for my iPad?

    How do I know my iPads are not compromised by viruses? Do I need protection, as I do for my PC.? If not, why not?

  • Why does the keyboard hide my iMessages?

    My new 6+ and ios8 is making it impossible for me to see the recent imessages.  I have to exit the app and come back so the keyboard goes away.  I can 'drag' them up, but I cannot get to the bottom. Any help appreciated. Thanks

  • Motorola Droid 3 Continues to Freeze

    Ive had my Droid 3 for a little over a year and yesterday it just started freezing up, especially when I open/shut the keyboard.  The only way to get it back is to pull the battery.  Ive tried uninstalling all of my unused applications, deleting my p

  • Pre populate the Primary contact field on Activity when created from an opp

    Is there a way to auto populate the Primary contact field when a task is created from an opportunity with a primary contact? Can it be done thru a custom weblink? I think Bob B. may have had some weblink documentation?