学面向对象,以java为设计语言,虽然老师不是讲java但是还是把java的基础知识大概讲了一下,速度当然很快,很少动手实践,这是自己抽时间照着课本做的图像化界面计算圆的周长面积。
1/* 2 *功能:测试GUI的使用,用户输入圆的半径,然后计算 3 *时间:2012.11.3 4 *作者:KDF5000 5 *文件名:TestGui.java 6 */ 7import java.awt.*; 8import java.awt.event.*; 9 10import javax.swing.*; 11import java.text.*; 12public class TestGui { 13 14 /** 15 * @param args 16 */ 17 public static void main(String[] args) { 18 // TODO Auto-generated method stub 19 new CalculateDomo(); 20 } 21 22} 23 24class CalculateDomo extends JFrame implements ActionListener 25{ 26 Circle theCircle; 27 JTextField messageText; 28 JTextArea resultArea; 29 JButton calButton; 30 JButton closeButton; 31 JButton clearButton; 32 33 public CalculateDomo() 34 { 35 super("计算圆的面积和周长"); 36 37 Container c=this.getContentPane(); 38 c.setLayout(new GridLayout(2,1)); 39 JPanel centerPanel=new JPanel(new FlowLayout()); 40 41 messageText =new JTextField(5); 42 JLabel messageLabel=new JLabel("请输入圆的半径: "); 43 calButton =new JButton("计算"); 44 closeButton =new JButton("关闭窗口"); 45 resultArea =new JTextArea("计算结果:",4,20); 46 47 centerPanel.add(messageLabel); 48 centerPanel.add(messageText); 49 centerPanel.add(calButton); 50 centerPanel.add(closeButton); 51 c.add(centerPanel); 52 c.add(resultArea); 53 54 //注册事件到容器 55 calButton.addActionListener(this); 56 closeButton.addActionListener(this); 57 58 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 59 this.setSize(360,200); 60 this.setVisible(true); 61 } 62 63 @Override 64 public void actionPerformed(ActionEvent e) { 65 // TODO Auto-generated method stub 66 if(e.getSource()==calButton) 67 calculate(); 68 if(e.getSource()==closeButton) 69 shutDown(); 70 } 71 72 private void calculate() 73 { 74 String message=messageText.getText(); 75 if(message.length()==0) 76 { 77 JOptionPane.showMessageDialog(null,"请输入半径!","提示",1); 78 } 79 else 80 { 81 int radius=Integer.parseInt(message); 82 theCircle=new Circle(radius); 83 int theRadius=theCircle.getRadius(); 84 double girth=theCircle.calGirth(); 85 double area=theCircle.calArea(); 86 87 resultArea.setText("计算结果如下:"); 88 resultArea.append("\n圆的半径是:"+theRadius); 89 resultArea.append("\n圆的周长是:"+new DecimalFormat("#.00").format(girth)); 90 resultArea.append("\n圆的面积是:"+new DecimalFormat("#.00").format(area)); 91 } 92 } 93 94 public void shutDown() 95 { 96 System.exit(0); 97 } 98 99} 100 101 102//圆类 103class Circle 104{ 105 private int radius; 106 107 public Circle(int radius) 108 { 109 this.radius=radius; 110 } 111 112 public int getRadius() { 113 return radius; 114 } 115 116 public void setRadius(int radius) { 117 this.radius = radius; 118 } 119 120 public double calArea() 121 { 122 return 3.14159*(this.radius^2); 123 } 124 125 public double calGirth() 126 { 127 return 2*3.14159*this.radius; 128 } 129}