1 import java.awt.*; 2 import java.awt.event.ActionEvent; 3 import java.awt.event.ActionListener; 4 5 import javax.swing.*; 6 import javax.swing.border.LineBorder; 7 8 9 public class Test_16_4 extends JFrame{ 10 JTextField JT1 = new JTextField(5); 11 JTextField JT2 = new JTextField(5); 12 JTextField JT3 = new JTextField(5); 13 JButton JB_add = new JButton("Add"); 14 JButton JB_sub = new JButton("Subtract"); 15 JButton JB_mul = new JButton("Multiply"); 16 JButton JB_div = new JButton("Divide"); 17 18 public Test_16_4(){ 19 JPanel JP1 = new JPanel(); 20 JPanel JP2 = new JPanel(); 21 22 NewListener nl = new NewListener(); 23 24 setLayout(new FlowLayout()); 25 JP1.add(new JLabel("Number 1")); 26 JP1.add(JT1); 27 JP1.add(new JLabel("Number 2")); 28 JP1.add(JT2); 29 JP1.add(new JLabel("Result")); 30 JP1.add(JT3); 31 JP1.setBorder(new LineBorder(Color.BLACK,1)); 32 33 setLayout(new FlowLayout()); 34 JP2.add(JB_add); 35 JP2.add(JB_sub); 36 JP2.add(JB_mul); 37 JP2.add(JB_div); 38 JP2.setBorder(new LineBorder(Color.black,1)); 39 40 setLayout(new BorderLayout(0,5)); 41 add(JP1,BorderLayout.CENTER); 42 add(JP2,BorderLayout.SOUTH); 43 44 JB_add.addActionListener(nl); 45 JB_sub.addActionListener(nl); 46 JB_mul.addActionListener(nl); 47 JB_div.addActionListener(nl); 48 } 49 public static void main(String[] args) { 50 // TODO Auto-generated method stub 51 Test_16_4 T1 = new Test_16_4(); 52 T1.pack(); 53 T1.setTitle("Test_16_4"); 54 T1.setLocationRelativeTo(null); 55 T1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 56 T1.setVisible(true); 57 } 58 59 class NewListener implements ActionListener{ 60 61 @Override 62 public void actionPerformed(ActionEvent e) { 63 // TODO Auto-generated method stub 64 double number1 = Double.parseDouble(JT1.getText()); 65 double number2 = Double.parseDouble(JT2.getText()); 66 if(e.getSource() == JB_add){ 67 JT3.setText(number1+number2+""); 68 }else if(e.getSource() == JB_sub){ 69 JT3.setText(number1-number2+""); 70 }else if(e.getSource() == JB_mul){ 71 JT3.setText(number1*number2+""); 72 }else if(e.getSource() == JB_div){ 73 JT3.setText(number1/number2+""); 74 } 75 } 76 77 } 78 }
效果图: