我一直在爲此苦苦掙扎了一段時間,我試圖構建一個使用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;
}
我試着幾件事情,但似乎沒有爲此工作,我最後只是空指針異常。對此有何建議?
你成功進入方法startBtnActionPerformed()? – Zyn
是的,它創建了網格。抱歉拿了一些代碼,因爲我使用Netbeans來創建GUI –