(1). 在应用程序窗体中安排两个文本框分别用来输入两个整数,两个按钮分别为“+”, “*”,一个结果标签。点击按纽“+”将两文本框的数据做加法运算;点击按钮“*”做 乘法运算,将结果显示在标签中,完成下面未完成的程序并要求给整体代码加上注释。
时间: 2024-05-23 12:14:34 浏览: 23
//导入必要的包
import java.awt.event.*;
import java.math.BigInteger;
import java.awt.*;
import javax.swing.*;
//定义一个类,继承JFrame
public class Caculate1 extends JFrame{
JTextArea text1,text2; //定义两个文本框
JButton jb1,jb2; //定义两个按钮
JLabel label; //定义一个标签
//构造函数
Caculate1(){
//初始化组件
text1=new JTextArea(2,4);
text2=new JTextArea(2,4);
jb1=new JButton("+");
jb2=new JButton("*");
label=new JLabel();
JSplitPane p1;
JPanel p2=new JPanel();
//给按钮添加监听器
jb1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取文本框中的值
String n1=text1.getText();
String n2=text2.getText();
try {
//将字符串转换为BigInteger类型
BigInteger num1=new BigInteger(n1);
BigInteger num2=new BigInteger(n2);
//计算结果并将其显示在标签中
label.setText((num1.add(num2)).toString());
}catch (Exception ee) {
//如果输入的不是整数,显示提示信息并清空文本框
label.setText("请输入整数");
text1.setText(null);
text2.setText(null);
}
}
});
jb2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取文本框中的值
String n1=text1.getText();
String n2=text2.getText();
try {
//将字符串转换为BigInteger类型
BigInteger num1=new BigInteger(n1);
BigInteger num2=new BigInteger(n2);
//计算结果并将其显示在标签中
label.setText((num1.multiply(num2)).toString());
}catch (Exception ee) {
//如果输入的不是整数,显示提示信息并清空文本框
label.setText("请输入整数");
text1.setText(null);
text2.setText(null);
}
}
});
//设置布局
setLayout(new GridLayout(3,1));
p1=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,text1,text2);
p1.setDividerLocation(117);
add(p1);
p2.setLayout(new GridLayout(1,2));
p2.add(jb1);
p2.add(jb2);
add(p2);
add(label);
setBounds(100,100,260,190);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)