作业1

绘制如图所示的界面。

要求:1、当单击“求和”按钮时,把“和”显示在“求和”按钮后的文本行中;

2、当单击“清除”按钮后,3个文本行的内容全部被清除。

 1 package zyframe;
 2 import java.awt.GridLayout;
 3 import java.awt.event.ActionEvent;
 4 import java.awt.event.ActionListener;
 5 import javax.swing.*;
 6 public class add implements ActionListener{
 7   JFrame f;
 8   JPanel p;
 9   JLabel l1,l2,l3,l4;
10   JButton b1,b2;
11   JTextField t1,t2,t3;
12   GridLayout g1;
13   String nowButton;
14   public add() {
15       f=new JFrame();
16       g1=new GridLayout(3,3);
17       p=new JPanel();
18       p.setLayout(g1);
19       l1=new JLabel("  加数1");
20       t1=new JTextField();
21       l3=new JLabel(" ");
22       l2=new JLabel("  加数2");
23       t2=new JTextField();
24       l4=new JLabel(" ");
25       b1=new JButton("求和");
26       t3=new JTextField();
27       b2=new JButton("清除");
28       f.add(p);
29       p.add(l1);
30       p.add(l2);
31       p.add(l3);
32       p.add(l4);
33       p.add(b1);
34       p.add(b2);
35       p.add(t1);
36       p.add(t2);
37       p.add(t3);
38   b1.addActionListener(this);
39   b2.addActionListener(this);
40   p.setVisible(true);
41   f.setSize(300, 200);
42   f.setVisible(true);
43   }
44   public static void main(String[] args) {
45       new add();
46   }
47   public void actionPerformed(ActionEvent e) {
48       nowButton=e.getActionCommand();
49       if(nowButton=="求和") {
50           t3.setText(count());
51       }
52       if(nowButton=="清除") {
53           t1.setText("");
54           t2.setText("");
55           t3.setText("");
56       }
57   }
58   public String count() {
59       double num1=Double.parseDouble(t1.getText());
60       double num2=Double.parseDouble(t2.getText());
61       double result=0;
62       result=num1+num2;
63       return String.valueOf(result);
64   } 
65 }

体会:发现关于那些按钮、文本框的位置一直都弄不对,百度了,也加了那些需要的,还是不对。不知道为什么。虽然不是很美观,但是还是弄出来了,还是有一点点小成就感,真的感觉编程对我来说,很困难。加油吧。

原文地址:https://www.cnblogs.com/rfvh/p/11114543.html