java使用综合布局实现简易乘法计算机
时间: 2023-08-12 18:19:39 浏览: 216
Java 具有加减乘除的简易计算器
5星 · 资源好评率100%
以下是Java使用综合布局实现简易乘法计算器的示例代码:
```java
import javax.swing.*;
import java.awt.*;
public class MultiplicationCalculator {
private JFrame frame;
private JTextField num1Field;
private JTextField num2Field;
private JLabel resultLabel;
public MultiplicationCalculator() {
frame = new JFrame("乘法计算器");
JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel num1Label = new JLabel("第一个数:");
num1Field = new JTextField();
JLabel num2Label = new JLabel("第二个数:");
num2Field = new JTextField();
JButton calculateButton = new JButton("计算");
resultLabel = new JLabel();
panel.add(num1Label);
panel.add(num1Field);
panel.add(num2Label);
panel.add(num2Field);
panel.add(new JLabel());
panel.add(calculateButton);
calculateButton.addActionListener(e -> {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 * num2;
resultLabel.setText(num1 + " * " + num2 + " = " + result);
} catch (NumberFormatException ex) {
resultLabel.setText("输入格式错误!");
}
});
JPanel resultPanel = new JPanel();
resultPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
resultPanel.add(resultLabel);
frame.add(panel, BorderLayout.CENTER);
frame.add(resultPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new MultiplicationCalculator();
}
}
```
这个程序使用了Swing框架,创建了一个包含两个文本框、一个按钮和一个标签的面板,并将面板和标签添加到了窗口中。当用户点击“计算”按钮时,程序会读取文本框中的数值,进行乘法运算,并将结果显示在标签中。你可以将这段代码复制到Java开发环境中进行编译和运行。
阅读全文