2014-05-24 102 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

回答