编写程序,创建如下图所示的图形界面。(要求实现功能)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class sum {
public static void main(String args[]){
ComputerFrame frame =new ComputerFrame();
frame.setTitle("求和");
frame.setBounds(500,500,800,800);
}
}
class ComputerFrame extends JFrame {
JTextField numberone;
JTextField numbertwo;
JTextField result;
JButton answer;
JButton clear;
Sumlistener sumlis;
Clearlistener clearlis;
ComputerFrame(){
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init(){
GridLayout Grid=new GridLayout(3,3);
setLayout(Grid);
add(new JLabel("数字1:"));
numberone=new JTextField(20);
add(numberone);
add(new JLabel(" "));
add(new JLabel("数字2:"));
numbertwo=new JTextField(20);
add(numbertwo);
add(new Label(" "));
answer=new JButton("求和");
result=new JTextField(20);
clear=new JButton("清除");
add(answer);
add(result);
add(clear);
sumlis=new Sumlistener(numberone,numbertwo,result);
clearlis=new Clearlistener(numberone,numbertwo,result);
answer.addActionListener(sumlis);
clear.addActionListener(clearlis);
}
}
class Sumlistener implements ActionListener{
JTextField numberone;
JTextField numbertwo;
JTextField result;
Sumlistener(JTextField one,JTextField two,JTextField res){
numberone=one;
numbertwo=two;
result=res;
}
public void actionPerformed(ActionEvent e){
double a=Double.parseDouble(numberone.getText().trim());
double b=Double.parseDouble(numbertwo.getText().trim());
String c=String.valueOf(a+b);
result.setText(c);
}
}
class Clearlistener implements ActionListener{
JTextField numberone;
JTextField numbertwo;
JTextField result;
Clearlistener(JTextField one,JTextField two,JTextField res){
numberone=one;
numbertwo=two;
result=res;
}
public void actionPerformed(ActionEvent e){
numberone.setText(" ");
numbertwo.setText(" ");
result.setText(" ");
}
}