Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

java - Should your class implement ActionListener or use an object of an anonymous ActionListener class

What's the best way for implementing the java.awt.event.ActionListener interface?

Have your class implement ActionListener and add this as an ActionListener:

class Foo implements ActionListener{

    public Foo() {
        JButton button = new JButton();
        button.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {

    }
}

Or add an object of an anonymous ActionListener class:

class Foo{

    public Foo() {
        JButton button = new JButton();
        button.addActionListener(new ActionListener() {     
            public void actionPerformed(ActionEvent e) {

            }
        });
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Some (jeanette/kleopatra) say to almost never use ActionListener, and to instead use Actions such as an AbstractAction. It's almost always a bad ideal to have your GUI class implement your listeners though as this breaks the Single Responsibility Principle and makes your code more difficult to maintain and extend,and so I strongly urge you not to do that.

So for example, an inner class for this:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;

class Foo {

   public Foo() {
       JButton button = new JButton(new ButtonAction("Action", KeyEvent.VK_A));
   }

   private class ButtonAction extends AbstractAction {
      public ButtonAction(String name, Integer mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         System.out.println("button pressed");
      }
   }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...