gpt4 book ai didi

使用 MVC 的 Java 点击计数器

转载 作者:搜寻专家 更新时间:2023-11-01 00:57:36 25 4
gpt4 key购买 nike

我正在尝试编写一个非常简单的 Java 示例来学习 MVC。这是一个 JButton,当点击它时会增加一个计数器并显示到目前为止的点击次数。

我将模型、 View 和 Controller 分解为单独的类,并认为我走在正确的道路上,但是当我单击按钮时,显示计数器的 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

最佳答案

我现在明白为什么了。您创建了两个不同的模型对象。一个在 Controller 中,一个在 Main() 中 - 是哪一个?

另一个建议.. 创建一个 MainController 类。这应该有您的 Main 方法。您的 main 方法创建了另一个 Controller ,负责创建您的 View 和模型。使用此 Controller 作为桥梁。

关于使用 MVC 的 Java 点击计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12785696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com