简体   繁体   中英

How to add an actionListener as a separate class in java

I've been working on a program and my master class with the bulk of the code has over 20 different "addActionListener" methods. How can I instead create this actionListener, itemStateChanged etc etc in a separate class but still perform as it should the way it does now. Any tips would be most welcome as I have run over 4000 lines of code already in this class :( Thank you!

public class MyActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent evt) {
        // actionPerformed here...
    }
}

You would use it like:

JButton button = new JButton();
button.addActionListener(new MyActionListener());

// OR

MyActionListener listener = new MyActionListener();
JButton button = new JButton();
button.addActionListener(listener);
class Mylistener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e){
         if (e.getSource() == someButton){
             // do something
         } else if (e.getSource() == someOtherButton){
             // do something
         } 
         // add more else if statements for other components
         // e.getSource() is the component that fires the event e.g. someButton
    }
}

Say you have two buttons

JButton someButton = new JButton("SOME BUTTON");
JButton someOtherButton = new JButtton("SOME OTHER BUTTON");

ActionListener listener = new MyListener();

someButton.addActionListener(listener);
someOtherButton.addActionListener(listener);

public MyClass extends JFrame {

    JButton someButton = new JButton("SOME BUTTON");
    JButton someOtherButton = new JButtton("SOME OTHER BUTTON");

    public MyClass(){

        ActionListener listener = new MyListener();
        someButton.addActionListener(listener);
        someOtherButton.addActionListener(listener);
    }

    class Mylistener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e){
         if (e.getSource() == someButton){
             // do something
         } else if (e.getSource() == someOtherButton){
             // do something
         } 
         // add more else if statements for other components
         // e.getSource() is the component that fires the event e.g. someButton
    }
}

You want to write a class which implements ActionListener. I could give you some code here with very little explanation, but I think it is best that I point you to the documentation here: http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

This link will give you some examples, and it will explain in detail how it is working. I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM