What is the common way to program action listeners?

前端 未结 6 1750
走了就别回头了
走了就别回头了 2021-01-06 01:10

I just started to learn how to use action listeners. To my understanding it works in the following way:

  1. There are some classes which contains \"addActionLis

6条回答
  •  轮回少年
    2021-01-06 01:22

    The most common way to handle this - judging from my own personal experience - is to simply create an anonymous inline class. Like this:

    listenedObject.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            // Your action handling code in here
        }
    });
    

    And often I've seen people place a call out to a method of the object containing the listenedObject. For example, in a Dialog that has a button:

    myOkayButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            okayButtonPressed();
        }
    });
    

    Then later in the dialog class:

    private void okayButtonPressed() {
        // Do what we need to do
    }
    

提交回复
热议问题