简体   繁体   中英

Create an object instance of a subclass from an external class

I've created an application that attaches events to a class of JButtons and other swing components that I instantiate many times in the GUI class.

The class MenuItemEventHandler is attached to each menu item. This works perfectly fine when the MenuItemEventHandler class is external. However i need to get it inside the GUI class instead of external.

I'm left with the issue of not being able to reference the event handler subclass from another external class in the same package. Is it possible to do so?

Below is the guiclass and eventhandler subclass

public class GUIClass {

// gui behaviour

    public class MenuItemEventHandler extends AbstractAction {

      private String aVariable;

      private static final long serialVersionUID = 1L;

      @Override
      public void actionPerformed(ActionEvent arg0) {
          // update a JList with added item
      }
}

Below is the external class i want to reference to the event handler so i can attach it to the collection of GUI objects.

It's making reference to the MenuItemEventHandler class that i cant achieve.

public class MenuItem {

ResturantGUI.MenuItemEventHandler action = ResturantGUI.new MenuItemEventHandler(this.item);
newButton.setAction(action);

// attach the event to the menu item

Two options, either you can make MenuItemEventHandler static :

so you declare your class like this:

public static class MenuItemEventHandler ...

or you create your event handler with a reference to an instance of the enclosing class GUIClass

Something:

GUIClass guiClass = new GUIClass();
MenuItemEventHandler handler = guiClass.new MenuItemEventHandler();

Personally, I find the second option usually the smell of a bad or incorrect design. I almost never use this kind of construction. Just an example of how you can "work around" this kind of pattern (there are others, it depends of the context):

public class GUIClass {
     public class MenutItemEventHandler {
           ...
     }

     public MenuItemEventHandler createEventHandler() {
           return new MenuItemEventHandler();
     }
}

...

 GUIClass guiClass = new GUIClass();
 MenuItemEventHandler handler = guiClass.createEventHandler();

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