通过按钮做加法运算

 1 package su;
 2 
 3 import java.awt.GridLayout;
 4 import java.awt.event.ActionEvent;
 5 import java.awt.event.ActionListener;
 6 
 7 import javax.swing.JButton;
 8 import javax.swing.JFrame;
 9 import javax.swing.JLabel;
10 import javax.swing.JPanel;
11 import javax.swing.JTextField;
12 
13 public class JiaFa implements ActionListener {
14     JFrame f;
15     JPanel p1,p2,p3;
16     JButton b1,b2;
17     JLabel l1,l2,l3,l4;
18     JTextField t1,t2,t3;
19     GridLayout g1,g2,g3,g4;
20     
21     public JiaFa() {
22         f = new JFrame();
23         p1 = new JPanel();
24         p2 = new JPanel();
25         p3 = new JPanel();
26         g1 = new GridLayout(1,3);
27         g2 = new GridLayout(3,1);
28         g3 = new GridLayout(3,1);
29         g4 = new GridLayout(3,1);
30         l1 = new JLabel("加数1");
31         l2 = new JLabel("加数2");
32         l3 = new JLabel();
33         l4 = new JLabel();
34         b1 = new JButton("求和");
35         b1.addActionListener(this);
36         b2 = new JButton("清除");
37         b2.addActionListener(this);
38         t1=new JTextField(5);
39         t2=new JTextField(5);
40         t3=new JTextField(5);
41         f.add(p1);
42         f.add(p2);
43         f.add(p3);
44         
45         f.setLayout(g1);
46         p1.setLayout(g2);
47         p2.setLayout(g3);
48         p3.setLayout(g4);
49 
50         p1.add(l1);
51         p1.add(l2);
52         p1.add(b1);
53         p2.add(t1);
54         p2.add(t2);
55         p2.add(t3);
56         p3.add(l3);
57         p3.add(l4);
58         p3.add(b2);
59         
60         
61         f.setSize(400,260);
62         f.setVisible(true);
63 
64         
65         
66     }
67 
68     public static void main(String[] args) {
69         new JiaFa();
70         //jiafa.jia();
71     }
72 
73     @Override
74     public void actionPerformed(ActionEvent e) {
75         // TODO 自动生成的方法存根
76         if(e.getSource()==b1){
77              int a,b,c;
78              a=Integer.parseInt(t1.getText());
79              b=Integer.parseInt(t2.getText());
80              c=a+b;
81              t3.setText(c+"");
82          }
83          if(e.getActionCommand().equals(b2.getText())){
84              t1.setText(null);
85              t2.setText(null);
86              t3.setText(null);
87          }
88      }
89 
90 }

猜你喜欢

转载自www.cnblogs.com/watch269397682/p/11020533.html