How does the 'actionPerformed' method get called without an explicit call to it?

后端 未结 2 1655
暗喜
暗喜 2021-02-19 22:11

I just started learning GUI with Swing and don\'t exactly understand how the actionPerformed method works. Consider the following code:

//code to cr         


        
2条回答
  •  滥情空心
    2021-02-19 23:08

    Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources.

    Here,the listener you registered, that is,

    button.addActionListener(this);
    

    gets added to a list of listeners, and when the JVM receives an event (click in this case), it calls the appropriate methods on all the listeners in the list.

    How does this happen? Well, i think you should read about Callback mechanism in java.

    You can also create your own listeners using Callback mechanism. Consider the below code:

    The code is for a credit-card app simulation.In the below code, the pinChanged() method gets called automatically when the changePin() method is called.

    public interface PinChangeListener {
        public void pinChanged();
    }
    
    public class CreditCard {
        public PinChangeListener pinChangeListener;
    
        private int pin;
    
        public changePin(int pin) {
            this.pin = pin;
            if (pinChangeListener != null) {
                pinChangeListener.pinChanged();
            }
        }
    }
    

    To connect a callback/listener to the credit card you just need to implement the PinChangeListener method:

    creditCard.pinChangeListener = new PinChangeListener() {
        public void pinChanged() {
            System.out.println("The pin has been changed");
        }
    };
    

    Similarly, when you attach a listener to a button, the click is detected by JVM,(You probably don't want to go into how the click is detected!) and the actionPerformed() of that listener which is attached is called by the JVM for you. Hope this clears.

提交回复
热议问题