Search code examples
javaprogramming-languages

JFrame subclass and ActionListener interface implementation


Why is extends JFrame implements ActionListener a bad design decision?


Solution

  • A couple points:

    • Extending a JFrame is probably a wrong approach
    • Implementing an ActionListener on an JFrame probably will lead to non-OOP code.

    Wrong Approach?

    If the idea is that an GUI application is being made, then, one is not making an extension of a JFrame, but actually writing an application.

    Therefore, the JFrame would be part of an application, not the application itself. Hence, the JFrame should be an object in the class.

    Implementing an ActionListener on an JFrame probably will lead to non-OOP code

    Consider the following case -- as the GUI application is starting to get large, and we're starting to add lots of buttons and menus which give rise to ActionEvents.

    If the JFrame itself were to get the events, then what would the actionPerformed method look like?

    Probably something like this:

    public void actionPerformed(ActionEvent e) {
      Object source = e.getSource();
    
      // Find out which component fired the event
      if (source == masterButton) {
        // ... do something
      } else if (source == anotherButton) {
        // ... do something else
      } else if (...)
        // ... and so on ...
      } else if (...)
        // ... and so on ...
      }
    }
    

    Yikes.

    We're going to start getting code that's tightly coupled to all the components in the application, and maintainability will be out the window in no time.


    If, for example, the GUI application had instances of ActionListers which responded to each component, then we'd be able to break up the actions and the coupling of the actionPerformed method with all the components in the GUI.

    For example:

    JButton masterButton = new JButton();
    masterButton.addActionListener(new MasterButtonActionListener());
    
    JButton anotherButton = new JButton();
    anotherButton.addActionListener(new AnotherButtonActionListener());
    

    This way, there will be ActionListeners for each button which presumably have different functionality. The responsibility of the MasterButtonActionListener would be to handle events from the masterButton -- it doesn't have to know about other buttons in the application.

    Also, this would promote reusability of the components in other applications or other part of the application without having to copy-and=paste parts of the monolithic if-else statement in the actionPerformed method.