我正在使用基於我將提供的代碼的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