3.参照例子15编写一个体现MVC结构的GUI程序。首先编写一个封装梯形类,然后编写一个窗口,要求窗口使用3个文本框和一个文本区为梯形对象中的数据提供视图,其中3个文本框用来显示和更新梯形对象的上底、下底和高,文本区对象用来显示梯形的面积。在窗口中有一个按钮,用户单击该按钮后,程序用3个文本框中的数据分别作为梯形对象的上底、下底和高,并将计算出的梯形的面积显示在文本区中。
时间: 2024-02-22 16:00:09 浏览: 26
好的,以下是我的解决方案:
首先,我们可以定义一个梯形类 `Trapezoid`,封装梯形的属性和方法:
```java
public class Trapezoid {
private double top, bottom, height;
public Trapezoid(double top, double bottom, double height) {
this.top = top;
this.bottom = bottom;
this.height = height;
}
public double getTop() {
return top;
}
public void setTop(double top) {
this.top = top;
}
public double getBottom() {
return bottom;
}
public void setBottom(double bottom) {
this.bottom = bottom;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return (top + bottom) * height / 2;
}
}
```
然后,我们可以编写一个窗口类 `TrapezoidView`,使用3个文本框和一个文本区来显示和更新梯形对象的数据,并提供一个按钮用来计算梯形的面积:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TrapezoidView extends JFrame implements ActionListener {
private JTextField topField, bottomField, heightField;
private JTextArea areaField;
private JButton calcButton;
private Trapezoid model;
public TrapezoidView() {
super("梯形计算器");
setLayout(new FlowLayout());
topField = new JTextField(10);
bottomField = new JTextField(10);
heightField = new JTextField(10);
areaField = new JTextArea(5, 20);
areaField.setEditable(false);
add(new JLabel("上底:"));
add(topField);
add(new JLabel("下底:"));
add(bottomField);
add(new JLabel("高:"));
add(heightField);
add(new JLabel("面积:"));
add(new JScrollPane(areaField));
calcButton = new JButton("计算");
add(calcButton);
calcButton.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(250, 250);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double top = Double.parseDouble(topField.getText());
double bottom = Double.parseDouble(bottomField.getText());
double height = Double.parseDouble(heightField.getText());
model = new Trapezoid(top, bottom, height);
areaField.setText(Double.toString(model.getArea()));
} catch (NumberFormatException ex) {
areaField.setText("输入有误!");
}
}
public static void main(String[] args) {
new TrapezoidView();
}
}
```
在窗口类中,我们使用了 `Trapezoid` 类作为模型,使用3个文本框和一个文本区来显示和更新模型的数据。在计算按钮的事件处理器中,首先尝试将输入的数据转换为 double 类型,如果输入有误则会抛出 NumberFormatException 异常,程序会捕获该异常并在文本区中显示错误提示。如果输入正确,则创建一个 `Trapezoid` 对象,并调用其 `getArea()` 方法计算梯形的面积,并将结果显示在文本区中。
这样,我们就实现了一个体现 MVC 结构的 GUI 程序,其中模型部分由 `Trapezoid` 类封装,视图部分由 `TrapezoidView` 窗口类实现,控制器部分则由计算按钮的事件处理器实现。