Java計算器的實現可以分為幾個步驟,包括界面設計、事件監聽以及邏輯處理,下面將詳細地介紹如何使用Java Swing庫創建一個簡單的圖形用戶界面(GUI)計算器。

1. 環境準備
在開始之前,[]確保你的開發[]環境已經安裝[]了Java Develo[]pment Kit (JDK),[]你還需要一個[]好的集成開發[]環境(IDE[]),比如In[]telliJ[] IDEA或E[]clipse[]來編寫和運行[]代碼。
2. 創建項目
在IDE中創建一個新的Java項目,并創建一個新類,命名為Calculator
。
3. 導入Swin[]g庫
Swing是Java的一個圖形用戶界面工具集,用于構建應用程序的GUI,為了使用Swing,你需要在類的開頭導入以下包:
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
4. 設計界面
我們將使用S[]wing組件[]來設計計算器[]的界面,以下[]是創建基本界[]面的步驟:
設置框架屬性[]
添加按鈕和文[]本框
設置框架屬性[]
我們需要創建一個JFrame
對象作為主窗口,并設置其基本屬性:
- public class Calculator {
- private JFrame frame;
- // ...
- public void createAndShowGUI() {
- frame = new JFrame("Java Calculator");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(300, 400);
- // ...
- }
- }
添加按鈕和文本框
接下來,我們要添加文本框和按鈕到JFrame
中:
- public class Calculator {
- // ...
- private JTextField textField;
- private JButton[] numberButtons = new JButton[10];
- private JButton addButton, subButton, mulButton, divButton, equalButton, clearButton;
- // ...
- public void createAndShowGUI() {
- // ...
- textField = new JTextField();
- frame.add(textField, BorderLayout.NORTH);
- JPanel panel = new JPanel();
- panel.setLayout(new GridLayout(4, 4));
- for (int i = 0; i < 10; i++) {
- numberButtons[i] = new JButton(String.valueOf(i));
- panel.add(numberButtons[i]);
- }
- addButton = new JButton("+");
- subButton = new JButton("");
- mulButton = new JButton("*");
- divButton = new JButton("/");
- equalButton = new JButton("=");
- clearButton = new JButton("Clear");
- panel.add(addButton);
- panel.add(subButton);
- panel.add(mulButton);
- panel.add(divButton);
- panel.add(equalButton);
- panel.add(clearButton);
- frame.add(panel, BorderLayout.CENTER);
- // ...
- }
- }
5. 事件監聽與處理
為了讓計算器[]工作,我們需[]要為每個按鈕[]添加事件監聽[]器,并為相應[]的事件定義行[]為,當用戶點[]擊數字按鈕時[],應該在文本[]框中顯示該數[]字。
我們可以為每個按鈕添加一個ActionListener
:
- public class Calculator {
- // ...
- private ActionListener buttonListener = new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- for (int i = 0; i < numberButtons.length; i++) {
- if (e.getSource() == numberButtons[i]) {
- textField.setText(textField.getText() + i);
- return;
- }
- }
- if (e.getSource() == clearButton) {
- textField.setText("");
- } else if (e.getSource() == addButton) {
- // handle addition operation
- } // ... handle other operations similarly
- }
- };
- // ...
- public void createAndShowGUI() {
- // ...
- for (int i = 0; i < numberButtons.length; i++) {
- numberButtons[i].addActionListener(buttonListener);
- }
- addButton.addActionListener(buttonListener);
- subButton.addActionListener(buttonListener);
- mulButton.addActionListener(buttonListener);
- divButton.addActionListener(buttonListener);
- equalButton.addActionListener(buttonListener);
- clearButton.addActionListener(buttonListener);
- // ...
- }
- }
6. 完善邏輯
我們需要完善按鈕的邏輯部分,以執行基本的算術操作,這包括解析表達式、計算結果,并將結果顯示在文本框中。
- public class Calculator {
- // ...
- private double computeResult(double firstOperand, double secondOperand, char operator) {
- switch (operator) {
- case '+': return firstOperand + secondOperand;
- case '': return firstOperand secondOperand;
- case '*': return firstOperand * secondOperand;
- case '/': return firstOperand / secondOperand;
- default: throw new IllegalArgumentException("Invalid operator");
- }
- }
- // ...
- private ActionListener buttonListener = new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- // ... previous code ...
- else if (e.getSource() == equalButton) {
- try {
- String[] parts = textField.getText().split("\\s*=\\s*");
- if (parts.length != 2) throw new IllegalStateException("Invalid expression");
- double firstOperand = Double.parseDouble(parts[0]);
- double secondOperand = Double.parseDouble(parts[1]);
- char operator = '+'; // default operator
- if (parts[0].contains("")) operator = '';
- else if (parts[0].contains("*")) operator = '*';
- else if (parts[0].contains("/")) operator = '/';
- double result = computeResult(firstOperand, secondOperand, operator);
- textField.setText(String.valueOf(result));
- } catch (NumberFormatException | IllegalStateException ex) {
- textField.setText("Error");
- }
- }
- }
- };
- // ...
- }
7. 運行程序
完成以上步驟[]后,你可以運[]行程序來測試[]計算器是否按[]預期工作,在[]IDE中通常[]有一個運行按[]鈕可以直接啟[]動你的程序。[]
總結
以上就是制作一個簡單的Java計算器的全過程,當然,還有很多可以改進的地方,比如錯誤處理、輸入驗證、更復雜的數學運算等,但本教程提供了一個基礎的框架,你可以在此基礎上繼續擴展和完善你的計算器應用。
評論一下?