2014-03-24 44 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()); 
}