通过Frame窗口实现简单的加法运算

桃扇骨 2022-05-09 10:38 200阅读 0赞

70

方法一:(比较繁)

  1. package GUI;
  2. /*通过Frame窗口实现简单的加法运算*/
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. public class TFMath {
  6. public static void main(String[] args) {
  7. new TFFrame().lanunFrame();
  8. }
  9. }
  10. class TFFrame extends Frame {
  11. public void lanunFrame() {
  12. TextField num1 = new TextField(10);
  13. TextField num2 = new TextField(10);
  14. TextField num3 = new TextField(15);
  15. Label lbplus = new Label("+");
  16. Button btnEqual = new Button("=");
  17. btnEqual.addActionListener(new MyMonitor(num1, num2, num3));
  18. setLayout(new FlowLayout());
  19. add(num1);
  20. add(lbplus);
  21. add(num2);
  22. add(btnEqual);
  23. add(num3);
  24. pack();
  25. setVisible(true);
  26. }
  27. }
  28. class MyMonitor implements ActionListener {
  29. TextField num1, num2, num3;
  30. public MyMonitor(TextField num1, TextField num2, TextField num3) {
  31. this.num1 = num1;
  32. this.num2 = num2;
  33. this.num3 = num3;
  34. }
  35. public void actionPerformed(ActionEvent e) {
  36. int n1 = Integer.parseInt(num1.getText());//转成整型计算
  37. int n2 = Integer.parseInt(num2.getText());
  38. num3.setText("" + (n1 + n2));//再将num3转成字符型
  39. }
  40. }

方法二:(持有对方的引用)

  1. package GUI;
  2. /*通过Frame窗口实现简单的加法运算--持有对方的引用*/
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. public class TFMath {
  6. public static void main(String[] args) {
  7. new TFFrame().lanunFrame();
  8. }
  9. }
  10. class TFFrame extends Frame {
  11. TextField num1, num2, num3;
  12. public void lanunFrame() {
  13. num1 = new TextField(10);
  14. num2 = new TextField(10);
  15. num3 = new TextField(15);
  16. Label lbplus = new Label("+");
  17. Button btnEqual = new Button("=");
  18. btnEqual.addActionListener(new MyMonitor(this));
  19. setLayout(new FlowLayout());
  20. add(num1);
  21. add(lbplus);
  22. add(num2);
  23. add(btnEqual);
  24. add(num3);
  25. pack();
  26. setVisible(true);
  27. }
  28. }
  29. class MyMonitor implements ActionListener {
  30. // TextField num1, num2, num3;
  31. // public MyMonitor(TextField num1, TextField num2, TextField num3) {
  32. // this.num1 = num1;
  33. // this.num2 = num2;
  34. // this.num3 = num3;
  35. // }
  36. TFFrame tf = null;
  37. public MyMonitor(TFFrame tf) { //持有对方的引用
  38. this.tf = tf;
  39. }
  40. public void actionPerformed(ActionEvent e) {
  41. int n1 = Integer.parseInt(tf.num1.getText());//转成整型计算
  42. int n2 = Integer.parseInt(tf.num2.getText());
  43. tf.num3.setText("" + (n1 + n2));//再将num3转成字符型
  44. }
  45. }

发表评论

表情:
评论列表 (有 0 条评论,200人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JavaScript加法运算

    1.运算元其一为字符串 > 字符串的拼接运算 2.运算元其一为数字 > 将另一个运算元转为数字再进行计算,如果为复杂数据类型则转为字符串 3.一元运算符