2014-03-24 45 views
0

我一直在爲此苦苦掙扎了一段時間,我試圖構建一個使用MVC模式的程序,該程序根據用戶輸入動態地創建一個按鈕(nxn)網格。然而,我不能把聽衆附加在他們身上。動態按鈕上的事件監聽器

編輯:我的意思,我想處理控制器類內部的事件,以符合MVC模式

查看

public class AIGameView extends javax.swing.JFrame { 

private AIGameModel model; 
private JButton[][] btn_arr; 

public AIGameView(AIGameModel m) { 
    model = m; 
    initComponents(); 
} 

@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() {...}         

private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {           
    options.setVisible(false); 
    int size = Integer.parseInt(size_field.getText()); 
    model.setSize(size); 
    btn_arr = new JButton[size][size]; 
    GameGUI.setLayout(new java.awt.GridLayout(size, size)); 
    for(int y = 0; y < size; y++) { 
     for(int x = 0; x < size; x++) { 
      btn_arr[y][x] = new JButton(); 
      btn_arr[y][x].setBackground(Color.white); 
      GameGUI.add(btn_arr[y][x]); 
      btn_arr[y][x].setVisible(true); 

     } 
    } 
    GameGUI.setVisible(true); 
    GameGUI.revalidate(); 
    GameGUI.repaint(); 
}   

控制器

public class AIGameController { 

private AIGameView view; 
private AIGameModel model; 
private JButton[][] buttons; 

public AIGameController(AIGameModel m, AIGameView v) { 
    view = v; 
    model = m; 
} 

我試着幾件事情,但似乎沒有爲此工作,我最後只是空指針異常。對此有何建議?

+0

你成功進入方法startBtnActionPerformed()? – Zyn

+0

是的,它創建了網格。抱歉拿了一些代碼,因爲我使用Netbeans來創建GUI –

回答

1

從您發佈至今的代碼,似乎你可以添加一個電話

btn_arr[y][x] = new JButton(); 
btn_arr[y][x].addActionListener(createActionListener(y, x)); 
... 

有了這樣

的方法
private ActionListener createActionListener(final int y, final int x) 
{ 
    return new ActionListener() 
    { 
     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      System.out.println("Clicked "+y+" "+x); 

      // Some method that should be called in 
      // response to the button click: 
      clickedButton(y,x); 
     } 
    }; 
} 

private void clickedButton(int y, int x) 
{ 
    // Do whatever has to be done now... 
} 
+0

但是這不會違背MVC模式嗎? –

+0

@ChrisCrossman There *有*是一些附加到按鈕的'ActionListener'。這是將「ActionListener」附加到按鈕上的「最小」方法,仍然保留有關哪個按鈕被點擊的信息。說得那樣:你只需要在'clickedButton'方法中調用'controller.doSomethingWith(x,y)'。或者是你的問題旨在從外部注入ActionListener? MVC在這一點上稍有爭議(無論如何,什麼是控制器?)。對我來說,每個'ActionListener'已經*是一個小控制器。讓我們看看別人說什麼。 – Marco13

+0

我試圖得到的東西在行:http://leepoint.net/notes-java/GUI/structure/40mvc.html但隨着我結束了一個空指針,因爲按鈕還沒有創建。但我明白你的意思。如果我找不到其他解決方案,我可能會在視圖中添加對控制器的引用。 –

0

當你要通過你的初始化循環:

for(int x = 0; x < size; x++) { 
    btn_arr[y][x] = new JButton(); 
    btn_arr[y][x].setBackground(Color.white); 
    GameGUI.add(btn_arr[y][x]); 
    btn_arr[y][x].setVisible(true); 
    btn_arr[y][x].addActionListener(new YourListener()); 
}