package add;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Add extends JFrame implements ActionListener{
/**
* @param args
*/
private JButton jButton1,jButton2;
private JTextField jTextField1,jTextField2,jTextField3;
private JLabel jLabel1,jLabel2,jLabel3;
public Add()
{
super("两个数求和");
jButton1=new JButton("提交");
jButton2=new JButton("重置");
jTextField1=new JTextField();
jTextField2=new JTextField();
jTextField3=new JTextField();
jLabel1=new JLabel("请分别输入两个数:");
jLabel1.setBounds(10, 10, 120, 20);
jLabel2=new JLabel("+");
jLabel3=new JLabel("=");
jTextField1.setBounds(30,50, 50,30);
jLabel2.setBounds(80, 50, 30, 30);
jTextField2.setBounds(90, 50, 50, 30);
jLabel3.setBounds(145, 50, 30, 30);
jTextField3.setBounds(160, 50, 50, 30);
jButton1.setBounds(50, 90, 70,20);
jButton2.setBounds(130, 90, 70, 20);
this.setLayout(null);
this.add(jLabel1);
this.add(jTextField1);
this.add(jLabel2);
this.add(jTextField2);
this.add(jLabel3);
this.add(jTextField3);
this.add(jButton1);
this.add(jButton2);
jButton1.addActionListener(this);
jButton2.addActionListener(this);
this.setLocation(200,200);
this.setSize(250,200);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Add();
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource()==jButton1) {
if (!this.jTextField1.getText().matches("[0-9.-]+")) {
JOptionPane.showMessageDialog(getParent(),"请输入要计算的数字!");
jTextField1.requestFocus();
}
else if (!this.jTextField2.getText().matches("[0-9.-]+")) {
JOptionPane.showMessageDialog(getParent(),"请输入要计算的数字!");
jTextField2.requestFocus();
}
else
{
String a=this.jTextField1.getText(),b=this.jTextField2.getText(),c;
double one,two,sum;
one =Double.parseDouble(a);
two=Double.parseDouble(b);
sum=one+two;
c=String.valueOf(sum);
this.jTextField3.setText(c);
}
}
else if(e.getSource()==jButton2) {
this.jTextField1.setText("");
this.jTextField2.setText("");
this.jTextField3.setText("");
}
}
}
运行图像: