使用MVC結構計算梯形面積
阿新 • • 發佈:2019-01-01
package com.ytu; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub WindowTrapezia win=new WindowTrapezia(); win.setTitle("使用MVC結構"); win.setBounds(100, 100,420,260); } } package com.ytu; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class WindowTrapezia extends JFrame implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try{ double a=Double.parseDouble(textA.getText().trim()); double b=Double.parseDouble(textB.getText().trim()); double c=Double.parseDouble(textC.getText().trim()); trapezia .setA(a); trapezia .setB(b); trapezia .setC(c); String area=trapezia .getArea(); showArea.append("梯形"+a+","+b+","+c+"的面積:"); showArea.append(area+"\n"); } catch(Exception ex){ showArea.append("\n"+ex+"\n"); } } Trapezia trapezia ; JTextArea showArea; JTextField textA,textB,textC; JButton controlButton; WindowTrapezia(){ trapezia=new Trapezia(); 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); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } package com.ytu; //梯形 public class Trapezia { double sideA,sideB,sideC,area; boolean isTrapezia; public void setA(double a) { // TODO Auto-generated method stub sideA=a; } public void setB(double b) { // TODO Auto-generated method stub sideB=b; } public void setC(double c) { // TODO Auto-generated method stub sideC=c; } public String getArea() { // TODO Auto-generated method stub area=(sideA+sideB)*sideC/2.0; return String.valueOf(area); } }