简体   繁体   English

从外部类创建子类的对象实例

[英]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. 我已经创建了一个应用程序,该应用程序将事件附加到我在GUI类中多次实例化的JButtons类和其他swing组件类。

The class MenuItemEventHandler is attached to each menu item. MenuItemEventHandler类附加到每个菜单项。 This works perfectly fine when the MenuItemEventHandler class is external. 当MenuItemEventHandler类是外部类时,这工作得很好。 However i need to get it inside the GUI class instead of external. 但是我需要在GUI类而不是外部中获取它。

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 下面是guiclass和eventhandler子类

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. 下面是我想引用事件处理程序的外部类,因此我可以将其附加到GUI对象的集合。

It's making reference to the MenuItemEventHandler class that i cant achieve. 它引用了我无法实现的MenuItemEventHandler类。

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 : 有两种选择,可以使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 或者您通过引用封闭类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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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