2014-05-24 104 views
0

我試圖讓我的頭在使用Swing在Java中的MVC設計模式,因爲我現在還沒有完全理解它,所以很困惑。我試圖讓我在eclipse中理解它,但是我在第68行有一個錯誤,我不知道爲什麼每次按下按鈕時都會出現很多錯誤,而不是計數器的遞增值。 感謝學習MVC設計模式

public class Model 
{ 
    int counter = 0; 

    int counter() 
    { 
     this.counter++; 
     return this.counter; 
    } 

} 

################################################################################# 
public class Controller 
{ 
    Model mRef; 
    View vRef; 

    public Controller(Model m, View v) 
    { 
     this.mRef = m; 
     this.vRef = v; 
    } 

    int inc() 
    { 
     mRef = new Model(); 
     return mRef.counter(); 
    } 

} 
###################################################################################### 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
@SuppressWarnings("serial") 
public class View extends JFrame 
{ 
    JPanel jp; 
    JButton jb1; 
    JLabel jl1; 
    GridBagConstraints c; 
    Controller con; 
    public View() 
    {  
     c = new GridBagConstraints(); 
     jp = new JPanel(); 
     jb1 = new JButton("First"); 
     jl1 = new JLabel("Label"); 
     jp.setLayout(new GridBagLayout());  
     add(jp);  

     c.gridx = 0; 
     c.gridy = 0; 
     jp.add(jb1, c); 

     jb1.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       System.out.println(con.inc()); 
      } 
     }); 
     c.gridx = 0; 
     c.gridy = 2; 
     jp.add(jl1, c); 

     setVisible(true); 
     pack(); 
    } 
} 
+1

con是空當你的actionPerformed方法被調用,但是,您認爲應該談論這個模型,控制器應在註冊按鈕的興趣和處理actionPerforned事件。當心,Swing並不嚴格地實現MVC,它更像M(VC) – MadProgrammer

+0

更多關於這個話題的內容可以在這裏找到(http://stackoverflow.com/a/3072979/230513)。 – trashgod

回答