当前位置:   article > 正文

Java实现计算器功能和界面_java实现计算器界面及功能

java实现计算器界面及功能

代码:

  1. package ch10;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. public class Demo02 extends JFrame implements ActionListener {
  7. JTextArea display;
  8. JButton[] buttons;
  9. String[] buttonLabels = {
  10. "1", "2", "3", "+","C",
  11. "4", "5", "6", "-","退格",
  12. "7", "8", "9", "*","1/x",
  13. "0", "+/-", ".", "/","="};
  14. String input = "";
  15. double num1, num2;
  16. char operator;
  17. public Demo02() {
  18. setTitle("计算器");
  19. setSize(400, 400);
  20. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  21. setLayout(new BorderLayout());
  22. display = new JTextArea();
  23. display.setFont(new Font("Serif", Font.PLAIN, 50));
  24. add(display, BorderLayout.NORTH);
  25. JPanel buttonPanel = new JPanel(new GridLayout(4,5,2,2));
  26. buttons = new JButton[20];
  27. for (int i = 0; i < 20; i++) {
  28. buttons[i] = new JButton(buttonLabels[i]);
  29. buttons[i].setFont(new Font("Serif", Font.BOLD, 18));
  30. buttons[i].setForeground(Color.BLUE);
  31. buttons[i].addActionListener(this);
  32. buttonPanel.add(buttons[i]);
  33. }
  34. buttons[4].setForeground(Color.RED);
  35. buttons[9].setForeground(Color.RED);
  36. buttons[19].setForeground(Color.RED);
  37. add(buttonPanel, BorderLayout.CENTER);
  38. }
  39. public void actionPerformed(ActionEvent e) {
  40. String action = e.getActionCommand();
  41. if (action.matches("[0-9]")) {
  42. input += action;
  43. display.setText(input);
  44. } else if (action.equals("C")) {
  45. input = input.substring(0, 0);
  46. display.setText(input);
  47. }else if (action.equals("退格")) {
  48. if (input.length() > 0) {
  49. input = input.substring(0, input.length() - 1);
  50. display.setText(input);
  51. }
  52. } else if (action.matches("[+\\-*/]")) {
  53. num1 = Double.parseDouble(input);
  54. operator = action.charAt(0);
  55. input = "";
  56. } else if (action.equals(".")) {
  57. if (!input.contains(".")) {
  58. input += ".";
  59. display.setText(input);
  60. }
  61. } else if (action.equals("=")) {
  62. num2 = Double.parseDouble(input);
  63. double result = 0;
  64. switch (operator) {
  65. case '+':
  66. result = num1 + num2;
  67. break;
  68. case '-':
  69. result = num1 - num2;
  70. break;
  71. case '*':
  72. result = num1 * num2;
  73. break;
  74. case '/':
  75. result = num1 / num2;
  76. break;
  77. }
  78. display.setText(String.valueOf(result));
  79. input = "";
  80. }
  81. }
  82. public static void main(String[] args) {
  83. Demo02 demo=new Demo02();
  84. demo.setVisible(true);
  85. }
  86. }

运行结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/275739
推荐阅读
相关标签
  

闽ICP备14008679号