题目
编写一个应用程序,包括三个文本框和四个按钮,分别是“加”、“减”、“乘”、“除”,单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。
布局
Code
package unit_9;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;
public class p10_3 {
public static void main(String[] args){
WindowBox win=new WindowBox("cal");
}
}
class WindowBox extends JFrame implements ActionListener {
Box box11, box12, box13, box21, box22;
JTextField text1,text2, text3;
JButton button1, button2, button3, button4;
WindowBox(String s){
setTitle(s);
text1=new JTextField(10);
text2=new JTextField(10);
text3=new JTextField(10);
button1=new JButton("加");
button2=new JButton("减");
button3=new JButton("乘");
button4=new JButton("除");
text1.addActionListener(this);
text2.addActionListener(this);
text3.addActionListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
box11=Box.createVerticalBox();
box11.add(new JLabel("number_1:"));
box11.add(Box.createVerticalStrut(8));
box11.add(new JLabel("number_2:"));
box11.add(Box.createVerticalStrut(8));
box11.add(new JLabel("ansewr:"));
box12=Box.createVerticalBox();
box12.add(text1);
box12.add(Box.createVerticalStrut(8));
box12.add(text2);
box12.add(Box.createVerticalStrut(8));
box12.add(text3);
box13=Box.createHorizontalBox();
box13.add(box11);
box13.add(Box.createHorizontalStrut(10));
box13.add(box12);
box21=Box.createHorizontalBox();
box21.add(button1);
box21.add(Box.createHorizontalStrut(8));
box21.add(button2);
box21.add(Box.createHorizontalStrut(8));
box21.add(button3);
box21.add(Box.createHorizontalStrut(8));
box21.add(button4);
box22=Box.createVerticalBox();
box22.add(box13);
box22.add(Box.createVerticalStrut(20));
box22.add(box21);
setLayout(new FlowLayout());
add(box22);
validate();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setBounds(700, 300, 300, 200);
}
public void actionPerformed(ActionEvent e){
String val1="", val2="";
try{
if(e.getSource()==button1)
{
val1=text1.getText();
val2=text2.getText();
BigInteger n1=new BigInteger(val1);
BigInteger n2=new BigInteger(val2);
n2=n1.add(n2);
text3.setText(n2.toString());
}
else if(e.getSource()==button2)
{
val1=text1.getText();
val2=text2.getText();
BigInteger n1=new BigInteger(val1);
BigInteger n2=new BigInteger(val2);
n2=n1.subtract(n2);
text3.setText(n2.toString());
}
else if(e.getSource()==button3)
{
val1=text1.getText();
val2=text2.getText();
BigInteger n1=new BigInteger(val1);
BigInteger n2=new BigInteger(val2);
n2=n1.multiply(n2);
text3.setText(n2.toString());
}
else if(e.getSource()==button4)
{
val1=text1.getText();
val2=text2.getText();
double v1=Double.parseDouble(val1);
double v2=Double.parseDouble(val2);
if(v2==0)
text2.setText("分母不能为0!");
else{
v2=v1/(v2*1.0);
text3.setText(Double.toString(v2));
}
}
}catch(NumberFormatException ee) {
text3.setText("请输入数字字符");
text1.setText(null);
text2.setText(null);
}
}
}
结果展示