2014-03-24 2 views
0

저는 잠시 동안이 문제에 시달렸습니다. MVC 패턴을 사용하는 프로그램을 만들려고합니다. 사용자 입력을 기반으로 버튼 격자 (nxn)를 동적으로 생성합니다. 그러나 나는 그들에게 청취자를 붙일 권리를 얻을 수는 없다.동적 버튼의 이벤트 리스너

편집 : 나는 컨트롤러

public class AIGameController { 

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

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

내가 해봤

보기

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(); 
}   

MVC 패턴에 부합하는 컨트롤러 클래스의 내부 이벤트를 처리 할 싶었다는 것을 의미 몇 가지,하지만이 아무것도 작동하지 않는 것 그리고 대부분 그냥 null 포인터 예외로 끝납니다. 이것에 대한 조언?

+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 버튼에 * ActionListener가 * 있어야합니다. 그리고 이것은 "ActionListener"를 버튼에 부착하고 어떤 버튼이 클릭되었는지에 대한 정보를 유지하는 "최소한의"방법입니다. 그 방법은 다음과 같다.'clickedButton' 메소드에서'controller.doSomethingWith (x, y)'만 호출하면된다. 아니면 외부에서 ActionListeners를 주입하는 것을 목표로하는 질문입니까? MVC는이 시점에서 약간 논란의 여지가 있습니다 (어쨌든 컨트롤러 란 무엇입니까?). 나에게있어 각 ActionListener는 이미 * 작은 컨트롤러이다. 다른 사람들이 말하는 것을 보자. – Marco13

+0

나는 줄의 뭔가를 얻으려고했다 : http://leepoint.net/notes-java/GUI/structure/40mvc.html하지만 버튼이 아직 만들어지지 않았으므로 nullpointer로 끝난다. 하지만 그 말이 무슨 뜻인지 이해합니다. 다른 솔루션을 찾을 수없는 경우보기의 컨트롤러에 대한 참조를 추가 할 수 있습니다. –

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()); 
}