8. 在应用程序窗体中安排两个文本框分别用来输入两个整数,三个按钮分别为“+”、“-” “clear”,一个结果标签。点击按纽“+”将两文本框的数据做加法运算;点击按钮“-”做减法运算,点击按钮“clear”清空文本框与计算结果。将运算式与结果显示在标签中。(提示:获取的文本可用Interger.parseInt()转换成整数进行计算。)用Java
时间: 2023-09-25 15:12:01 浏览: 80
这是一个简单的 Java GUI 应用程序,实现了两个整数的加减乘除运算。代码如下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField num1Field, num2Field, resultField;
private JButton addButton, subButton, mulButton, divButton, clearButton;
public Calculator() {
super("Calculator");
// Create the input fields
num1Field = new JTextField(10);
num2Field = new JTextField(10);
// Create the buttons
addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
clearButton = new JButton("Clear");
// Create the result field
resultField = new JTextField(10);
resultField.setEditable(false);
// Add the components to the content pane
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(new JLabel("Number 1: "));
c.add(num1Field);
c.add(new JLabel("Number 2: "));
c.add(num2Field);
c.add(addButton);
c.add(subButton);
c.add(mulButton);
c.add(divButton);
c.add(clearButton);
c.add(new JLabel("Result: "));
c.add(resultField);
// Add action listeners to the buttons
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
divButton.addActionListener(this);
clearButton.addActionListener(this);
// Set the size and make the window visible
setSize(300, 150);
setVisible(true);
}
// Handle button clicks
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 + num2;
resultField.setText(Integer.toString(result));
} else if (e.getSource() == subButton) {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 - num2;
resultField.setText(Integer.toString(result));
} else if (e.getSource() == mulButton) {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 * num2;
resultField.setText(Integer.toString(result));
} else if (e.getSource() == divButton) {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 / num2;
resultField.setText(Integer.toString(result));
} else if (e.getSource() == clearButton) {
num1Field.setText("");
num2Field.setText("");
resultField.setText("");
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
运行程序后,会弹出一个窗口,可以输入两个整数,然后点击加、减、乘、除按钮进行运算,点击 Clear 按钮可以清空输入和结果。
阅读全文