2012-04-19 63 views
0

什麼缺點這類黑客,除了不能聽許多按鈕與一個監聽器:實施的ActionListener在一個JButton孩子

this.buttons = new LinkedHashMap<String, JButton>(); 

    this.buttons.put("create", 
     new Activator<MainMenu>("Create new definition", this) { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       this.controller.createDefinition(); 
      } 
     } 
    ); 

回答

2

我沒有看到這個額外的類的優點,它可以很容易地被一個簡單的方法所取代。

this.buttons.put("create", 
    createButton("Create new definition", new ActionListener(){...}); 

public JButton createButton(String label, ActionListener actionListener){ 
    JButton button = new JButton(label); 
    button.addActionListener (actionListener); 
    return button; 
} 

這也需要一個匿名類,就像在你的代碼,但避免了額外的(怪異)類(在這個意義上,按鈕動作監聽器,這是不應該被連接到什麼怪異其他)。

+0

我的主要誤解是「ActionListener只是一個接口,因此無法實例化」。我應該檢查是否可以創建一個匿名的ActionListener。謝謝! – sdkfasldf 2012-04-19 06:54:21

+1

@vrode:該示例不_instantiate_接口;它會創建一個匿名的內部類來實現接口。 – trashgod 2012-04-19 10:03:50

2

public class Activator<E> extends JButton implements ActionListener { 

     protected E controller; 

     public Activator(String label, E controller) { 
      super(label); 
      this.addActionListener(this); 
      this.controller = controller; 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      return; 
     } 

    } 

一個按鈕被實例化

我可以看到的一個明顯的缺點是,如果您剛創建按鈕並將偵聽器添加到偵聽器中,您將獲得額外的類和更多的代碼。當使用Activator時,仍然有一個內聯監聽器實現,那麼它是否有用(即使使用這種模式的多個按鈕)?你完全需要Activator課程嗎?