java组件及事件处理中MVC结构提供了很大的便利
模型-控制-视图(Model-View-Controlle)简称MVC结果,是一种先进的设计结构,是Trygve ReensKaug教授于1978年最早开发的一个基本结构,其目的是以会话形式提供方便的GUI支持。MVC语言首先出现在Smalltalk编程语言中。
MVC是一种通过三个不同部分构造一个软件或组件的理想方法。
模型(model)用于存储数据的对象
试图(view)为模型提供数据显示的对象
控制器(controller)处理用户交互操作,对于用户操作做出响应,让模型和视图进行必要的交互,即通过视图修改,获取模型中的数据;当模型中的数据变化时,让视图进行更新。
使用MVC结构计算三角形的面积:
import sun.security.mscapi.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Example {
public static void main(String[] args) {
WindowTriangle win = new WindowTriangle();
win.setTitle("MVC结构");
win.setBounds(100, 100, 420, 260);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WindowTriangle extends JFrame implements ActionListener {
Triangle triangle; //Model
JTextField textA, textB, textC; //View
JTextArea showArea; //View
JButton controlButton; //Controller
WindowTriangle() {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void init() {
triangle = new Triangle();
textA = new JTextField(5);
textB = new JTextField(5);
textC = new JTextField(5);
showArea = new JTextArea();
controlButton = new JButton("计算面积");
JPanel pNorth = new JPanel();
pNorth.add(new JLabel("边A:"));
pNorth.add(textA);
pNorth.add(new JLabel("边B:"));
pNorth.add(textB);
pNorth.add(new JLabel("边C:"));
pNorth.add(textC);
pNorth.add(controlButton);
controlButton.addActionListener(this);
add(pNorth, BorderLayout.NORTH);
add(new JScrollPane(showArea), BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
double a = Double.parseDouble(textA.getText().trim());
double b = Double.parseDouble(textB.getText().trim());
double c = Double.parseDouble(textC.getText().trim());
triangle.setA(a); //更新数据
triangle.setB(b);
triangle.setC(c);
String area = triangle.getArea();
showArea.append("三角形" + a + "," + b + "," + c + "的面积:");
showArea.append(area + "\n");//更新视图
} catch (Exception ex) {
showArea.append("\n" + ex + "\n");
}
}
}
public class Triangle {
double sideA, sideB, sideC, area;
boolean isTriangle=true;
public String getArea() {
if (isTriangle) {
double p = (sideA + sideB + sideC) / 2.0;
area = Math.sqrt(p * (p - sideA) * (p - sideB) * (p - sideC));
return String.valueOf(area);
} else {
return "无法计算面积";
}
}
public void setA(double a) {
sideA = a;
if (sideA + sideB > sideC && sideA + sideC > sideB && sideC + sideB > sideA)
isTriangle = true;
else
isTriangle = false;
}
public void setB(double b) {
sideB = b;
if (sideA + sideB > sideC && sideA + sideC > sideB && sideC + sideB > sideA)
isTriangle = true;
else
isTriangle = false;
}
public void setC(double c) {
sideC= c;
if (sideA + sideB > sideC && sideA + sideC > sideB && sideC + sideB > sideA)
isTriangle = true;
else
isTriangle = false;
}
}
转载:https://blog.csdn.net/qq_41910353/article/details/102239960
查看评论