编写一个应用程序,有一个标题为“计算”的窗口,窗口的布局为Flowlayout布局。设计四个按钮,分别命名为加减乘除,另外,在窗口中还要三个文本框。单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。要求处理NumberFormatException异常。
时间: 2024-11-09 21:19:37 浏览: 24
在Java中,你可以使用Swing库创建这样一个简单的图形用户界面(GUI)程序。下面是一个简化的示例代码,展示了如何实现这个需求:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorApp extends JFrame {
private JButton addBtn, subtractBtn, multiplyBtn, divideBtn;
private JTextField textField1, textField2, resultField;
public CalculatorApp() {
// 初始化窗口和布局
setTitle("计算");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// 创建组件并添加到窗口
textField1 = new JTextField(10);
textField2 = new JTextField(10);
resultField = new JTextField(20);
resultField.setEditable(false); // 防止用户直接修改结果
addBtn = new JButton("+");
subtractBtn = new JButton("-");
multiplyBtn = new JButton("*");
divideBtn = new JButton("/");
for (JButton button : Arrays.asList(addBtn, subtractBtn, multiplyBtn, divideBtn)) {
button.addActionListener(new OperationListener());
add(button);
}
add(textField1);
add(textField2);
add(resultField);
setSize(300, 200);
setLocationRelativeTo(null);
}
private class OperationListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String num1 = textField1.getText();
String num2 = textField2.getText();
try {
double num1Double = Double.parseDouble(num1);
double num2Double = Double.parseDouble(num2);
switch (e.getActionCommand()) {
case "+":
resultField.setText(String.valueOf(num1Double + num2Double));
break;
case "-":
resultField.setText(String.valueOf(num1Double - num2Double));
break;
case "*":
resultField.setText(String.valueOf(num1Double * num2Double));
break;
case "/":
if (num2Double != 0) {
resultField.setText(String.valueOf(num1Double / num2Double));
} else {
JOptionPane.showMessageDialog(CalculatorApp.this,
"除数不能为零,请输入有效数值!", "错误", JOptionPane.ERROR_MESSAGE);
}
break;
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(CalculatorApp.this,
"请输入有效的数字!", "错误", JOptionPane.ERROR_MESSAGE);
resultField.setText("");
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CalculatorApp().setVisible(true));
}
}
```
阅读全文