简体   繁体   中英

Is it possible to import a listener from another class in java

If I have a java class and I want to use a listener from another class, how do I do this? For example, if I had two JFrames and had a button in one of them could I get it to do something in another class

You could create a public method in one class

public void addSomeButtonActionListener(ActionListener listener) {
    someButton.addActionListener(listener);
}

and this would allow other objects to add listeners to your button of interest. Please note that if a button has multiple listeners added to it, there is no guarantee as to which one will fire first or in any of the order of firing.

Alternatively, you could use the PropertyListener support that comes intrinsic to all Swing components, create your own bound properties, and allow outside classes to add PropertyChangeListeners to the class of interest, listening for changes in your bound properties. For more on this, please check out this tutorial . Note, if you go this route, and if your class extends a Swing component, then there is no need to write your own addPropertyChangeListener(...) or removePropertyChangeListener(...) since these methods as well as a SwingPropertyChangeSupport field are already an intrinsic component of all Swing components. If your class doesn't extend a Swing component, then yes, you'll need to write the methods above, but you can still use the SwingPropertyChangeSupport of one of your GUI class's critical components.

The latter solution is the one I like, but I find I more often listen to bound properties of my models rather than my views.

If you need more detail, please tell us more about your code and problem.

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