我正在尝试编写一个非常简单的 Java 示例来学习 MVC。它是一个 JButton,单击时会增加一个计数器并显示到目前为止的单击次数。
我将模型、视图和控制器分解为单独的类,并认为我走在正确的道路上,但是当我单击按钮时,显示计数器的 JLabel 继续保持在 0。
有人可以快速查看一下为什么应该显示点击次数的 JLabel 始终保持为 0 吗?
谢谢
View
package mvc;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class View extends javax.swing.JFrame {
private JButton jButton1;
private JLabel jLabel1;
private Controller c;
private Model m;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Controller c = new Controller();
Model m = new Model();
View inst = new View(c,m);
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public View(Controller c, Model m) {
super();
this.c = c;
this.m = m;
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
{
jButton1 = new JButton();
getContentPane().add(jButton1, "Center");
jButton1.setText("Click");
jButton1.setBounds(314, 180, 101, 34);
jButton1.addActionListener(c);
}
{
jLabel1 = new JLabel();
getContentPane().add(getJLabel1());
jLabel1.setText("Click Count = " + c.getClickCount());
jLabel1.setBounds(439, 183, 91, 27);
}
pack();
this.setSize(818, 414);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
public JLabel getJLabel1() {
return jLabel1;
}
}
End View
Controller class
package mvc;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller implements ActionListener
{
Model m;
View v;
public Controller()
{
m = new Model();
v = new View(this, m);
}
@Override
public void actionPerformed(ActionEvent arg0)
{
if (arg0.getSource() == "Click")
{
m.addClick();
v.getJLabel1().setText("Click count = " + getClickCount());
}
}
public int getClickCount()
{
return m.getClicks();
}
}
End Controller class
Model class
package mvc;
public class Model
{
private int clicks;
public Model()
{
clicks = 0;
}
public void addClick()
{
clicks++;
}
public int getClicks()
{
return clicks;
}
}
End Model class