How to add event listener?

i want to add event listener when i click on a button in mxml, the event listener should be added in the action script file, how to do this?
can anyone help? urgent!!!

Hi Lakshmi,
You can do this just put all the script in the mxml block in seperate AS file as shown below... Observe that I have included an AS file named Script.as and removed the script block form mxml and moved to this Script.as file. Place the Script.as file in your src folder ....
// Main mxml file....
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="onCreationComplete()">
    <mx:Script source="Script.as"/>
<mx:TextArea id="textArea" width="300" height="100" />
<mx:Button id="myButton" label="Click ME"/>
</mx:Application>
//Script.as file
import mx.controls.Alert;
            private function onCreationComplete():void
             myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
            private function onButtonClick(event:MouseEvent):void
             Alert.show("Button is Clicked");
Thanks,
Bhasker

Similar Messages

  • How to add event listener to datagrid ROW

    I need to know if it is possible to have the datagrid rows execute a state change.
    For example: I have a datagrid populated with various items, when one row is selected I want it to change the state of a part of the canvas it is in.
    How is this possible? I can not give the row an id so I would not be able to say "when row is selected change state" because there is no way to tell what row is selected.
    Help please. Thanks.

    See Flex 4 and MXDataGridItemRenderer.

  • How to know which leaf node i click and how to add a listener to each node?

    hi! hello to all members, i have a problem i know how to create a listener, but i dont know how to add a listener to each leaf node. here is the scenario i want to do, i have a JTree where theres a topic that you can select on each leaf node, so when the user click the specific topic it will open another JFrame,which i dont know how to do it also, that its! the next problem will be how do i know which leaf node i select, so that i can open a right topic before the JFrame will open?please, i am very need this to solve quickly as possible. thanks again to all members.

    What you have to do is to add a mouse listener on your JTree. Try something like this:
    tree.addMouseListener(new java.awt.event.MouseAdapter() {
             public void mouseReleased(MouseEvent e) {
                tree_mouseReleased(e);
    private void tree_mouseReleased(MouseEvent e) {
          TreePath selPath = tree.getSelectionPath();
          // Check If the click is the Right Click
          if (e.isPopupTrigger() == true) {
          // This is your right Click
           else {
                     // This is your Left Click
    }Your other problem: Set the userObject on nodes and on left click compare it with your object, if it matches, display the appropriate file. Alternatively, if your nodes are unique, you can match the names to open the file.
    Hope this Helps
    Regard
    Raheel

  • How to add event to calendar?

    how to add event to calendar?  No plus sign at top of window.

    See the user guide:  http://manuals.info.apple.com/en_US/iphone_user_guide.pdf

  • How to add events in JTable fields

    Hello friends i m working with file transfer client server project in my college.In my client part i have used JTable with AbstractTableModel.
    In my JTable it list the current directory files and directories under current directory .
    now how can i add events to the the directories that it shows on JTable so that when i click on directory it displays files under that selected directory.
    can anyone help me in that.
    I will send you my code for that project if anyone can help me.
    please help me to do that

    You can handle row selections with selection listener but if you want to handle double clicks you can use something similar to this:
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e)
    int column = table.columnAtPoint(e.getPoint());
    int row = table.rowAtPoint(e.getPoint());
    Object cellValue = table.getValueAt(row, column); 
    // Insert files below clicked row
    });Please, be more patient in the future -you would probably get an answer if you just posted to any of these two forums.

  • Urgent: How to add event listeners to a null object?

    I have an object that is lazy loaded, and therefore starts out null.
    How can I add an event listener onto this null object, so that it fires whenever the object is instantiated?
    WHY does arrayCollection.addEventListener(CollectionEvent.COLLECTION_CHANGED, function) not work??
    Thanks!
    C

    C,
    the answer to your question "WHY does arrayCollection.addEventListener(CollectionEvent.COLLECTION_CHANGED, function) not work??" is that addEventListener is not a static method, ie it has to be attached to an actual instance. I agree that in your situation it would be handy to have it as static, something like ArrayCollection.addEventListener(etc) but I'm not at all sure that is a good plan in general, as usually we want events to fire from an actual instance of the class, not generically. A quick look through the adobe docs has convinced me there are not many static methods at all, and none that appear to help you.
    I take it from your description that you don't know exactly when the collection is instantiated? But presumably though you do have a point where new is called? Or something equivalent like populating it from something else?
    Richard

  • How to add a Listener to the JLabel

    Hi,
    I am doing a Designer module in which i want to Listen Focus gained event on JLabel. For that i have added FocusListener to the JLabel but it does not listen to this event. (i think because of JLabels extraodinary property).
    So How to add listener to the JLabel?

    Set the label to be focusable. This will allow it to gain focus from the
    keyboard (from pressing TAB, for example), but not from being clicked on.
    It's easy to give some demo code than to explain it:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class LabelListening extends MouseAdapter implements FocusListener {
        private static final String TEXT_KEY = "jlabel_text_key";
        public void focusGained(FocusEvent e) {
            JLabel label = (JLabel) e.getComponent();
            String text = (String) label.getClientProperty(TEXT_KEY);
            label.setText("<html><u>" + text + "</u></html>");
        public void focusLost(FocusEvent e) {
            JLabel label = (JLabel) e.getComponent();
            String text = (String) label.getClientProperty(TEXT_KEY);
            label.setText(text);
        public void mousePressed(MouseEvent e) {
            e.getComponent().requestFocusInWindow();
        public static void main(String[] args) {
            LabelListening app = new LabelListening();
            JPanel contentPane = new JPanel();
            for(int i=0; i<4; ++i) {
                String text = "label " + i;
                JLabel label = new JLabel(text);
                label.putClientProperty(TEXT_KEY, text);
                label.setFocusable(true);
                label.addFocusListener(app);
                label.addMouseListener(app);
                contentPane.add(label);
            JButton btn = new JButton("a button");
            btn.setBorderPainted(false);
            btn.setContentAreaFilled(false);
            btn.setMargin(new Insets(0,0,0,0));
            contentPane.add(btn);
            final JFrame f = new JFrame("");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(contentPane);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }In this example, I have the focused label underlined. I don't
    know what your context is, but it may be simpler just to work with
    buttons instead. I "undecorate" a button in this example to make it look
    similar to a label.

  • Which object in hierarchy should add event listener?

    Hello all,
    I'm quite new to the whole OOP thing, and one of the things I keep wondering about is this:
    Which class should listen for events if the choice is between a contained class or a containing class?
    For example:
    An instance of Game holds an instance of Board which holds an array of instances of fields.
    This might be a scenario for a simple board game, I guess (In my case I am working on Reversi).
    A player should click a field to place a piece on it. I could let the Field class listen for the click event,
    but when a player places a piece, other pieces might have to flip, so an object at a higher level should handle this (board / game / maybe another object).
    So in order to make sure this happens, I could let the field object listen for the event and than tell the higher-level-object to do his thing, or I could
    let the higher-level-object add an event listener on the field object, and than both flip the nescesary pieces as well as tell the field to add a piece on itself.
    Could anyone explain which and why either solution (or maybe a third on) is better?
    Thanks for your time!

    qdudu wrote:
    Hello all,
    I'm quite new to the whole OOP thing, and one of the things I keep wondering about is this:
    Which class should listen for events if the choice is between a contained class or a containing class?The class that can respond to the events should implement the Listener.
    For example:
    An instance of Game holds an instance of Board which holds an array of instances of fields.
    This might be a scenario for a simple board game, I guess (In my case I am working on Reversi).
    A player should click a field to place a piece on it. I could let the Field class listen for the click event,
    but when a player places a piece, other pieces might have to flip, so an object at a higher level should handle this (board / game / maybe another object).Sounds like Board would be a good choice, then.
    So in order to make sure this happens, I could let the field object listen for the event and than tell the higher-level-object to do his thing, or I could
    let the higher-level-object add an event listener on the field object, and than both flip the nescesary pieces as well as tell the field to add a piece on itself.Sounds like the field object can't do much except forward the event to the real handler. In that case I'd vote for the higher-level-object as the listener.
    Could anyone explain which and why either solution (or maybe a third on) is better?In this case it could be either one. Try both and see. But based on the little you've posted here I'd vote for the higher-level-object, the Board.
    %

  • How to add event handler to JTable?

    I need an event listener that tells me whenever a cell has been edited. Does anyone have any ideas on how to implement this. There doesn't seem to be much documentation on the subject.
    Thanks in advance..
    dosteov

    Hello,
    It looks like you are interested in the
    BeforeAttachmentAdd event of Outlook items. It is fired before an attachment is added to an instance of the parent object. So, you can analyze the attachment object passed as a parameter and set then Cancel argument - set
    it to true to cancel the operation; otherwise, set to false to allow the Attachment to
    be added.
    Also the Outlook object model provides the
    AttachmentAdd event for Outlook items. It is fired when an attachment has been added to an instance of the parent object. You can also analyze the attachment object passed as a parameter to the event handler. You will not be able to
    cancel the action in that case.

  • How to add event in Date type bean

    Hi,
    I have created two date items - start date and end date.
    now I want to add event in these items?
    how can I add event in date type bean?
    Pls help..
    Thanks
    Amit

    Hi Swati,
    Yes, I have two OAMessageTextInput bean of Type Date.
    How can I set event by --StartDateBean.setEnterClientAction(ClientAction);
    I am unable to pass parameter of type "ClientAction" in .setEnterClientAction.
    how can I do this. If I declare by
    ClientAction DateEvent = null;
    then
    StartDateBean.setEnterClientAction(DateEvent);
    then it doesn't gives me any error but I am unable to initialize the value in "ClientAction" except null.
    How can I do this?
    Pls Help?
    Thanks
    Amit

  • How to add events to a ordinary html tag

    How can i add a event to ordinary tag
    Ex:
    public void encodeBegin(FacesContext context) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    writer.startElement("div", this);
    writer.writeAttribute("id", getClientId(context), null);
    String width = (String)getAttributes().get("width");
    String height = (String)getAttributes().get("height");
    String style = (String)getAttributes().get("style");
    style= (style!=null) ? style + ";" : "";
    if (width != null) style += "width:" + width + ";";
    if (height != null) style += "height:" + height+ ";";
    writer.writeAttribute("style", style, null);
    String styleClass = (String)getAttributes().get("styleClass");
    if (styleClass!=null)
    writer.writeAttribute("class", styleClass, null);
    String title = (String)getAttributes().get("title");
    if (title!=null)
    writer.writeAttribute("title", title, null);
    public void encodeEnd(FacesContext context) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    writer.write("<input type=\"button\" name=\"but\"/>");
    writer.endElement("div");
    i want to add event and bean for the <<< writer.write("<input type=\"button\" name=\"but\"/>"); >>>line of code, which is nothing but a button. I can added using JSF concept. but the requirement is like this. I have to add normal html tag for which i have to use bean and events as well.
    Can anyone give suggestion for this

    I will give a clear example
    writer.write("<h:outputText id=\"txt\" value=\"Just a Display\" />");
    writer.write("div");
    this 2 lines is in endcodeEnd method. The output text wont display the msg.
    even i am writing before the end tag
    Here is the full code
    ================
    public void encodeBegin(FacesContext context) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    writer.startElement("div", this);
    writer.writeAttribute("id", getClientId(context), null);
    String width = (String)getAttributes().get("width");
    String height = (String)getAttributes().get("height");
    String style = (String)getAttributes().get("style");
    style= (style!=null) ? style + ";" : "";
    if (width != null) style += "width:" + width + ";";
    if (height != null) style += "height:" + height+ ";";
    writer.writeAttribute("style", style, null);
    String styleClass = (String)getAttributes().get("styleClass");
    if (styleClass!=null)
    writer.writeAttribute("class", styleClass, null);
    String title = (String)getAttributes().get("title");
    if (title!=null)
    writer.writeAttribute("title", title, null);
    public void encodeEnd(FacesContext context) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    writer.write("<h:outputText id=\"txt\" value=\"Just a message\" />");
    writer.endElement("div");
    writer.write("<h:outputText id=\"txt\" value=\"Just a message\" />");
    This line is not executing
    kindly reply me..
    my mail id is [email protected]

  • How does custom event listener work.

    Hi,
    With reference to Custom Event Listener, I wanted to know the behaviour of Custom Listener whether they are sync or async.
    For Example :
    Suppose i have a method1() which has the listener1() get invoked at some operation at line #1 of method();
    The task of listener1() takes 2 minutes aprox.
    Then my question is does method1() waits until listener1() finishes its task(2 Minutes) ?
    What is he default behavior of listner1()
    Can we change the default behavior of custom listners ?
    Thanks & Regards,

    jwenting wrote:
    rephrase your question in gramatically (and preferably syntactically) correct English so people can actually understand what you're asking.You took the words straight out of my mouth
    Mel

  • Add event listener to HTTPService call

    Hi – I am using a HTTP service within my flex
    application.
    My HTTPServeice is connecting to an XML file:
    <mx:HTTPService
    id="myResults"
    url="
    http://localhost/myResults.xml"
    resultFormat="e4x"
    result="resultHandler(event)" />
    the data within the XML file is constantly changing (the
    structure remains the same, but the actual data within the
    structure of the XML changes), therefore I am refreshing my
    HTTPService results every 5 seconds:
    [Bindable]
    public var myDataFeed:XML;
    private function initApp():void
    var timedProcess:uint = setInterval(refreshResults, 5000);
    private function refreshResults():void
    myResults.send();
    private function resultHandler(event:ResultEvent):void
    myDataFeed = event.result as XML;
    My problem is that sometimes the XML file needs longer than 5
    seconds to load / refresh the data (as it is quite heavy)
    etc… therefore I want to implement some sort of event
    listener on the HTTPService to let the application know when the
    results have been refreshed so I can restrict / the 5 second
    refresh taking place until the previos refresh is complete
    etc…
    is this possible – to set an event listener to a
    HTTPService to know when it has completed refreshing results from
    an XML file???
    Thanks,
    Jon.

    result="resultHandler(event)" <--- is already an event
    listener.
    btw if you have a live XML you might want to consider xml
    socket connection so that server will push data to client .(lot
    more efficient)

  • How to add a listener for frame change

    hello
    Im quite new to jmf, and im writing a code which uses the webcam, but im stuck at a point where i want a listener which is called whenever the frame changes in the visualcomponent. so basically im looking for a frame changed listener to be added to the visual component instead of using a loop or a timer or something.
    i just need a method to be called constantly along the stream coming from the webcam but which is consistent with the changing of the frames.
    i would really appreciate any kind of help.
    thank you

    i thought there would be a listener or something ready to do thisThere is. It's the Rendered interface, which has a callback everytime data is received. If you want to create a custom renderer that is triggered everytime data is available, you set a processor to use your renderer and when data is available, your process command will be called. Same as an event listener...but it's very advanced stuff to implement the renderer interface.
    for example if u want to record a video ull need to capture every frame as soon as it comesNo, the video doesn't come to you a frame at a time. The video is already encoded somehow when you get it, so it's coming in as a stream just like it'll be going out to the file... It's a stream of bytes, not a stream of images... You're not digitizing here, you're transcoding.

  • How to remove event listener when all the MoviClip are off the stage

    Hi i am newbie to as3,
        I am creating animation using as3 in which i duplicate the circle ten time,then pushing into an array and giving random motion. When all the duplicate object goes outside the stage then i should remove the event listener. But right now when one duplicate object goes off the stage the event listener is removed. Thanks in advance

    //---------code for creating random bubble movement------//
    var bubbleNo:Number = 10;
    var vx:Number = .3;
    var vy:Number = .5;
    var bubbles:Array = new Array();
    var bubbleRadius:Number = 9;
    var myColor:ColorTransform = this.transform.colorTransform;
    init();
    function init():void {
    for(var i:Number = 0; i<bubbleNo; i++){
              var bubble = new newBall();
    bubble.x = Math.random() * stage.stageWidth;
    bubble.y = Math.random() * stage.stageHeight;
    //bubble.color = Math.random
    //trace("bubble.x=="+bubble.x+"bubble.y=="+bubble.y);
    bubbles.push(bubble);
    myColor.color = Math.random() * 0xFFFFFF
    bubble.transform.colorTransform = myColor;
    addChild(bubble);
              addEventListener(Event.ENTER_FRAME,createBubble);
    //addEventListener(Event.ENTER_FRAME,createBubble);
    function createBubble(event:Event):void{
    for(var k:Number = bubbles.length-1; k>0; k--){
              var bubble = (newBall)(bubbles[k]);
              bubble.x += vx;
              bubble.y += vy;
              if(bubble.x - 18 > stage.stageWidth || bubble.x + 18 < 0  || bubble.y - 18 > stage.stageHeight || bubble.y + 18 < 0){
                        removeChild(bubble);
                        bubbles.splice(k, 1);
                        //trace("out"+bubbles.length);
                        if(bubbles.length <= 0 );
                                  removeBubble();
                                  trace(bubbles.length);
                                  //removeEventListener(Event.ENTER_FRAME,createBubble)
                        trace("all Bubbles cleared");
                        function removeBubble():void{
                                  removeEventListener(Event.ENTER_FRAME,createBubble)

Maybe you are looking for

  • Date From and Date TO

    Hi All, I have created two parameters P_Date_From and P_Date_TO. I am using as below in SQL query to restrict data. Where Ordered_On_Date>=:P_Date_From and  Ordered_On_Date<=:P_Date_TO Its working fine if I supply the dates but erroring out when we r

  • Need to download the report output list to a Excel file.

    Hi,    I have a report output list, which i need to download to an Excel file, could any body suggest how to do this with out writing the ws_download. My report data is coming from two internal tables, one internal table for left side reprt display a

  • Why can't I use Galaxy SII here??

    Am looking at 'Straight Talk' offered by Wal-Mart via Verizon. I would not be able to use a Galaxy SII in the Montana area...but could in Dallas Texas...why? I understand there are 4 different types of towers- I CAN use a Galaxy SII in Montana with A

  • How can I purchase songs from other country?

    How can I purchase songs from other country?

  • Internet load balancing with two machine (NLB)

    i have install two TMG 2010 and one is manger and one managed , but seems once manager down , other server not passing the traffic with vip , my question is does it supported like NLB with two machine ?