修改程序Example11_13.java,要求按照MVC开发模式来编写,设计一个MathListener.java,实现对ActionEvent事件的监听,不再使用窗体做监视器对象
时间: 2024-03-15 11:44:16 浏览: 101
TestActionEvent2.rar_TestActionEvent_java event handl_监听器
下面是重构后的程序,按照MVC模式进行了设计:
Triangle.java (Model)
```java
public class Triangle {
private double a, b, c;
public Triangle() {
a = b = c = 0;
}
public void setA(double a) {
this.a = a;
}
public void setB(double b) {
this.b = b;
}
public void setC(double c) {
this.c = c;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
```
WindowTriangle.java (View)
```java
import javax.swing.*;
import java.awt.*;
public class WindowTriangle extends JFrame {
private JTextField txtA, txtB, txtC, txtArea;
private JButton btnCalc;
public WindowTriangle() {
setTitle("Triangle");
setSize(250, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel(new GridLayout(4, 2));
p1.add(new JLabel("Side A:"));
txtA = new JTextField(5);
p1.add(txtA);
p1.add(new JLabel("Side B:"));
txtB = new JTextField(5);
p1.add(txtB);
p1.add(new JLabel("Side C:"));
txtC = new JTextField(5);
p1.add(txtC);
p1.add(new JLabel("Area:"));
txtArea = new JTextField(10);
txtArea.setEditable(false);
p1.add(txtArea);
JPanel p2 = new JPanel();
btnCalc = new JButton("Calculate");
p2.add(btnCalc);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
}
public double getA() {
return Double.parseDouble(txtA.getText());
}
public double getB() {
return Double.parseDouble(txtB.getText());
}
public double getC() {
return Double.parseDouble(txtC.getText());
}
public void setArea(double area) {
txtArea.setText(String.format("%.2f", area));
}
public void addMathListener(MathListener listener) {
btnCalc.addActionListener(listener);
}
}
```
MathListener.java (Controller)
```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MathListener implements ActionListener {
private Triangle model;
private WindowTriangle view;
public MathListener(Triangle model, WindowTriangle view) {
this.model = model;
this.view = view;
}
@Override
public void actionPerformed(ActionEvent e) {
try {
double a = view.getA();
double b = view.getB();
double c = view.getC();
model.setA(a);
model.setB(b);
model.setC(c);
double area = model.getArea();
view.setArea(area);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(view, "Invalid input!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
```
Example11_13.java (Main)
```java
public class Example11_13 {
public static void main(String[] args) {
Triangle model = new Triangle();
WindowTriangle view = new WindowTriangle();
MathListener controller = new MathListener(model, view);
view.addMathListener(controller);
view.setVisible(true);
}
}
```
重构后,程序按照MVC模式进行了设计,MathListener.java实现了对ActionEvent事件的监听,不再使用窗体做监视器对象。
阅读全文