简体   繁体   中英

better way to implement inner class with listeners

I have a main class with inner classes. This is a swing/GUI application.

I have inner classes that are swing related such as extending JPanel, JDialog etc...

Inside the inner classes I have anonymous classes such as action listeners which I have to set and get data from the outer class..

For example main class has inner class and inside inner class I have an anonymous listener class such as this:

public class Main extends JApplet {
 //etc...
  private class CTable extends JPanel {
      CDialog td;
      private JPopupMenu menu;
      public CTable(String title, AbstractTableModel tableModel) {
         //etc...
         menu = new JPopupMenu();
         JMenuItem menuItem = new JMenuItem("Test");
         menu.add(menuItem);
         //etc...
         menuItem.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent event) {
              CTable.this.td = new CDialog("Test");
              CTable.this.td.setVisible(true);
           }
         });
     }

}

My only question is only related to whether its good practice to access the variable like this: CTable.this.td = new CDialog("Test"); CTable.this.td.setVisible(true); ...from anonymous classes and suggestions on different implementation strategies/design patterns.

I know anonymous inner classes are the Swing idiom since forever, but I've never liked them.

Personally, I think the listeners are part of the controller. I prefer the Swing components to be pure view and let the controller instantiate them and give them the listeners they need to act as the controller chooses. Don't make the view have to worry about how it communicates with the controller or where it lives.

CTable.this.td.setVisible(true);

There is a rule called the Law of demeter . This states that you should only access classes directly. By stepping over several objects to get to the desired method, you're creating tight coupling between your classes, which makes it harder to change individual classes in the future.

A design pattern I would suggest for this could be a Proxy class . A proxy class acts as a buffer between two classes, and means that both classes communicate with one another via the Proxy class

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