简体   繁体   中英

Java Swing anonymous actions

Is it ok to set actions like in the code sample below? Are there any possible garbage collection problems that might be caused by this? And if not what would be the best way to do this?

btnAwesomeButton=new JButton(new AbstractAction("Awesome Button") {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        //Do stuff here
        //Refer to the components on parent windows through ParentWindowClass.this.componentName      
    }

});

This is a very common idiom. There are no garbage collection issues, provided you don't stash a reference to the AbstractAction subclass instance somewhere (like a hash table) where it will persist after actionPerformed returns.

Yes, it's perfectly normal. This is what we call anonymous inner class . There is no garbage collection with this issue at all.

Yes, there are potential gotchas in garbage collection with this. However, the other answers are correct in that it is a standard idiom.

When you create an anonymous inner class like this it has a hidden reference to the outer class. That means that as long as this button exists with that action, the outer class will still be referenced, as with everything that that outer class references.

This is typically not a problem in practice, however, since the outer class will usually be the window or panel where this button resides, and the button will be around as long the panel is. That is why it is the standard idiom - it is typically fine.

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