在线文字转语音网站:无界智能 aiwjzn.com

如何用Java GUI开发一个计算器

如何用Java GUI开发一个计算器

下面是一个简单的Java GUI计算器的示例代码: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CalculatorGUI extends JFrame implements ActionListener { private JPanel panel; private JTextField textField; private JButton[] buttons; private String[] buttonLabels = { \t"7", "8", "9", "/", \t"4", "5", "6", "*", \t"1", "2", "3", "-", \t"0", ".", "=", "+" }; private String currentInput = ""; private double result = 0; private String operator = ""; public CalculatorGUI() { panel = new JPanel(); panel.setLayout(new GridLayout(4, 4)); textField = new JTextField(); textField.setEditable(false); buttons = new JButton[buttonLabels.length]; for (int i = 0; i < buttonLabels.length; i++) { buttons[i] = new JButton(buttonLabels[i]); buttons[i].addActionListener(this); panel.add(buttons[i]); } add(textField, BorderLayout.NORTH); add(panel, BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Calculator"); setSize(300, 400); setLocationRelativeTo(null); setVisible(true); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); switch (command) { case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": currentInput += command; textField.setText(currentInput); break; case ".": if (!currentInput.contains(".")) { currentInput += "."; } textField.setText(currentInput); break; case "/": case "*": case "-": case "+": operator = command; result = Double.parseDouble(currentInput); currentInput = ""; textField.setText(""); break; case "=": double secondOperand = Double.parseDouble(currentInput); switch (operator) { case "/": result /= secondOperand; break; case "*": result *= secondOperand; break; case "-": result -= secondOperand; break; case "+": result += secondOperand; break; } currentInput = String.valueOf(result); textField.setText(currentInput); break; default: break; } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new CalculatorGUI(); } }); } } 可以通过创建CalculatorGUI对象来实例化计算器GUI,并使用`SwingUtilities.invokeLater()`方法在事件分发线程中启动应用程序。