以下是一個簡單的 Java 計算器的實現:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator {
private JFrame frame;
private JTextField inputField;
private JButton[] numberButtons;
private JButton[] operatorButtons;
private JButton calculateButton;
private JButton clearButton;
public Calculator() {
frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setLayout(new GridLayout(5, 4));
inputField = new JTextField();
frame.add(inputField);
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
frame.add(numberButtons[i]);
}
operatorButtons = new JButton[4];
operatorButtons[0] = new JButton("+");
operatorButtons[1] = new JButton("-");
operatorButtons[2] = new JButton("*");
operatorButtons[3] = new JButton("/");
for (int i = 0; i < 4; i++) {
frame.add(operatorButtons[i]);
}
calculateButton = new JButton("=");
frame.add(calculateButton);
clearButton = new JButton("C");
frame.add(clearButton);
frame.setVisible(true);
// 設置按鈕的監聽器
for (int i = 0; i < 10; i++) {
int finalI = i;
numberButtons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
inputField.setText(inputField.getText() + finalI);
}
});
}
for (int i = 0; i < 4; i++) {
int finalI = i;
operatorButtons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
inputField.setText(inputField.getText() + operatorButtons[finalI].getText());
}
});
}
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String expression = inputField.getText();
double result = 0;
// TODO: 實現計算邏輯
// 這里只是一個示例,只實現了加法運算
if (expression.contains("+")) {
String[] numbers = expression.split("\\+");
double num1 = Double.parseDouble(numbers[0]);
double num2 = Double.parseDouble(numbers[1]);
result = num1 + num2;
}
inputField.setText(String.valueOf(result));
}
});
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
inputField.setText("");
}
});
}
public static void main(String[] args) {
new Calculator();
}
}
這個計算器使用了 Java 的 Swing 庫來創建圖形界面。它包含一個文本框用于顯示輸入和計算結果,數字按鈕用于輸入數字,操作按鈕用于輸入運算符,計算按鈕用于執行計算,清除按鈕用于清除輸入。在計算按鈕的監聽器中,可以自己實現計算邏輯。上面的示例只實現了簡單的加法運算,你可以根據需要自己擴展實現其他運算。