我正在使用基于我将提供的代码的MVC。我遇到了问题,因为我对这个主题相当陌生。我能够表达观点,但是当谈到制作模型时,这对我来说有点复杂。我需要一些关于如何将以下代码转换为MVC的指导,以便我可以练习和学习。我已经呆了好几个小时了,我决定来这里寻求帮助。如何将普通类转换为MVC?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class SayHi extends JFrame implements MouseListener{
// components
protected JLabel helloLabel = new JLabel("Hello");
protected JTextField userInputTextField = new JTextField(20);
private JButton sayHiBtn = new JButton("Say Hi");
/** Constructor */
SayHi() {
//... Layout the components.
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(new JLabel("Enter your name"));
content.add(userInputTextField);
content.add(sayHiBtn);
content.add(helloLabel);
// Add a mouse listener to the button
sayHiBtn.addMouseListener(this);
//... finalize layout
this.setContentPane(content);
this.pack();
this.setTitle("Simple App - Not MVC");
// The window closing event should probably be passed to the
// Controller in a real program, but this is a short example.
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Methods I am forced to implement because of the MouseListener
public void mouseClicked(MouseEvent e) {
helloLabel.setText("Hello " + userInputTextField.getText());
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
public static void main(String[] args){
SayHi s = new SayHi();
s.setVisible(true);
}
}
您不会将单个“常规”类转换为MVC。您至少需要3个课程(模型,视图和控制器)。不过,在没有框架的情况下创建模型可能只是简单地创建一个'ArrayList'或类似的东西。 –
ChiefTwoPencils