简体   繁体   中英

Can I add my ActionListeners to separate class windows?

I currently have all my action listeners declared under my constructor, but I'm starting to get a lot of them building up. Is it possible to create a new classes (via the default package window) and have them all there separately?

This seems obvious to me, I have tried this and I get no errors, but my application wont load when I do, it says its open but theres nothing there.

Here is a link to my code that is compilable.. I have commented out anything that uses other classes (there isn't much), if I have missed any just comment them out.

https://shrib.com/Tum8kjgH?v=nc

Thanks!

The most simple solution is to declare your listeners each in their own class. For example, for some button:

public class SomeButtonActionListener implements ActionListener{

    private InternalFrame iFrame;

    public SomeActionListener(InternalFrame iFrame){
        this.iFrame = iFrame;
    }

    public void actionPerformed(ActionEvent ae) {
        //TODO
        //Example: iFrame.getSomeButton().doSomething();
    }
}

Note that in this way, you need to expose getter methods for all swing components you need to access from your listeners (an alternative is to send the specific components needed as arguments to the listener when constructor is called).

In your InternalFrame you can add the listeners as:

someButton.addActionListener(new SomeButtonActionListener(this));

Also you can put all your listeners in a specific package like yourapp.listeners .

EDIT

A more specific example:

public class AddRoomListener implements ActionListener{
    private InternalFrame iFrame;

    public AddRoomListener(InternalFrame iFrame){
        this.iFrame = iFrame;
    }
    public void actionPerformed(ActionEvent event) { 
        iFrame.getIntFrame2().setVisible(true);
        iFrame.getIntFrame2().toFront();
    }
}

In this case you need to declare the getIntFrame2() getter in the InternalFrame class.

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