99行代码
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Calculator extends JFrame { private String[] labels = { "%","√","x²","1/x","CE","C","←","÷", "7","8","9","×","4","5","6","-","1","2","3","+","±","0",".","=" }; private String a = "", b = "", op = ""; JPanel panel; JTextField comp; public Calculator() { setLayout(new BorderLayout()); Font font = new Font("Sanserif", Font.BOLD, 25); comp = new JTextField("0"); comp.setHorizontalAlignment(JTextField.RIGHT); comp.setBounds(10, 8, 271, 50); comp.setFont(font); panel = new JPanel(); panel.setLayout(null); panel.add(comp); for (int i = 0; i < 24; i++) { JButton button = new JButton(labels[i]); if (labels[i].length() == 1 && labels[i].charAt(0) >= '0' && labels[i].charAt(0) <= '9' || labels[i] == ".") { button.addActionListener(new InsertAction()); button.setFont(font); } else button.addActionListener(new CommandAction()); int x = i % 4 * 70 + 10, y = i / 4 * 48 + 70; button.setLayout(null); button.setBounds(x, y, 60, 40); panel.add(button); } add(panel, BorderLayout.CENTER); } private class InsertAction implements ActionListener { public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s != "." || b.indexOf(".") == -1) b += s; comp.setText(b); } } private class CommandAction implements ActionListener { public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s == "+" || s == "-" || s == "×" || s == "÷") { a = b; b = ""; op = s; comp.setText(s); } else if (s == "=") { double A = Double.parseDouble(a); double B = Double.parseDouble(b); switch (op) { case "+":A += B; break; case "-":A -= B; break; case "×":A *= B; break; case "÷":A /= B; break; } long C = Math.round(A); a = b = Math.abs(C - A) < 1e-12 ? C + "" : A + ""; comp.setText(b); } else if (s == "±" || s == "√" || s == "x²" || s == "1/x") { double B = Double.parseDouble(b); switch (s) { case "±":B = -B; break; case "√":B = Math.sqrt(B); break; case "x²":B *= B; break; case "1/x":B = 1 / B; break; } long C = Math.round(B); b = Math.abs(C - B) < 1e-12 ? C + "" : B + ""; comp.setText(b); } else if (s == "←") { if (b.length() != 0) { b = b.substring(0, b.length() - 1); comp.setText(b); } } else if (s.charAt(0) == 'C') { a = b = op = ""; comp.setText("0"); } } } public static void main(String[] args) { EventQueue.invokeLater(()-> { JFrame frame = new Calculator(); frame.setTitle("Calculator"); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setSize(297, 390); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }); } }
效果图
按键顺序参照Win10计算器:
ps:除了%不知道有啥用,还有CE和C的功能写的一样之外,其他都实现了
暂时还没有发现逻辑错误