同步计算输入的各个数的总和与平均值

 1 package Com.TomTest;
 2 
 3 
 4 import java.awt.FlowLayout;
 5 import java.awt.event.*;
 6 import javax.swing.JButton;
 7 import javax.swing.JFrame;
 8 import javax.swing.JLabel;
 9 import javax.swing.JTextField;
10 
11 /**
12  * @author 同步计算输入的各个数的总和与平均值
13  */
14 public class TomTest_04 extends JFrame {
15     private static final long serialVersionUID = 6515574844960224544L;
16     JTextField input = new JTextField(30);
17     JTextField output = new JTextField(30);
18     JButton close = new JButton("关闭");
19     JButton reset = new JButton("清空");
20     public TomTest_04() {
21         setupGUI();
22     }
23     public void setupGUI() {
24         this.setTitle("计算总和与平均值");
25         this.setLayout(new FlowLayout());
26         this.add(new JLabel("数据"));
27         this.add(input);
28         this.add(new JLabel("结果"));
29         this.add(output);
30         this.add(close);
31         this.add(reset);
32         setSize(400, 130);
33         input.addKeyListener(new KeyAdapter() {
34             public void keyReleased(KeyEvent e) {
35                 String str = input.getText();
36                 if (str.equals("") || str == null) {
37                     output.setText("");
38                 } else {
39                     String num[] = str.split(" ");
40                     int sum = 0;
41                     double avg = 0.0;
42                     for (int i = 0; i < num.length; i++) {
43                         sum += Integer.parseInt(num[i]);
44                     }
45                     avg = sum * 1.0 / num.length;
46                     output.setText("Sum=" + sum + ", Avg=" + avg);
47                 }
48             }
49         });
50         close.addMouseListener(new MouseAdapter() {
51             public void mouseClicked(MouseEvent arg0) {
52                 System.exit(0);
53             }
54         });
55         reset.addMouseListener(new MouseAdapter() {
56             public void mouseClicked(MouseEvent arg0) {
57                 input.setText("");
58                 output.setText("");
59             }
60         });
61         setVisible(true);
62         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
63     }
64     public static void main(String[] args) {
65         new TomTest_04();
66     }
67 }

 

posted @ 2018-08-07 16:55  borter  阅读(199)  评论(0编辑  收藏  举报