Thứ Năm, 12 tháng 2, 2009

Ví dụ Applet : Cộng - Trừ - Nhân - Chia

AppletCalc

Khi nhấn vào các nút sẽ thực hiện các phép tính tương ứng.

CongTruNhanChia.java

  1: import java.awt.*;
  2: import java.applet.*;
  3: import java.awt.event.*;
  4: 
  5: public class CongTruNhanChia extends Applet implements ActionListener {
  6:   
  7:   private Label lblSo1, lblSo2, lblKQ;
  8:   private Button btnCong, btnTru, btnNhan, btnChia;
  9:   private TextField txtSo1, txtSo2, txtKQ;
 10:   
 11:   public void init() {
 12:     setLayout(null);
 13:     lblSo1 = new Label("So 1: ");
 14:     lblSo2 = new Label("So 2: ");
 15:     lblKQ = new Label("Ket Qua: ");
 16:     txtSo1 = new TextField();
 17:     txtSo2 = new TextField();
 18:     txtKQ = new TextField();
 19:     btnCong = new Button("Cong");
 20:     btnTru = new Button("Tru");
 21:     btnNhan = new Button("Nhan");
 22:     btnChia = new Button("Chia");
 23:     
 24:     add(lblSo1); lblSo1.setBounds(30, 50, 30, 20);
 25:     add(txtSo1); txtSo1.setBounds(90, 50, 80, 20);
 26:     add(lblSo2); lblSo2.setBounds(30, 80, 30, 20);
 27:     add(txtSo2); txtSo2.setBounds(90, 80, 80, 20);
 28:     add(lblKQ); lblKQ.setBounds(30, 110, 50, 20);
 29:     add(txtKQ); txtKQ.setBounds(90, 110, 80, 20);
 30:     add(btnCong); btnCong.setBounds(30, 140, 60, 24);
 31:     add(btnTru); btnTru.setBounds(100, 140, 60, 24);
 32:     add(btnNhan); btnNhan.setBounds(170, 140, 60, 24);
 33:     add(btnChia); btnChia.setBounds(240, 140, 60, 24);
 34:     
 35:     btnCong.addActionListener(this);
 36:     btnTru.addActionListener(this);
 37:     btnNhan.addActionListener(this);
 38:     btnChia.addActionListener(this);
 39:     
 40:     
 41:   }
 42:   
 43:   public void actionPerformed(ActionEvent e) {
 44:     float so1, so2, kq=0;
 45:     so1 = Integer.parseInt(txtSo1.getText());
 46:     so2 = Integer.parseInt(txtSo2.getText());
 47:     if (e.getSource()==btnCong)
 48:       kq = so1 + so2;
 49:     else if (e.getSource()==btnTru)
 50:       kq = so1 - so2;
 51:     else if (e.getSource()==btnNhan)
 52:       kq = so1 * so2;
 53:     else if (e.getSource()==btnChia)
 54:       kq = so1 / so2;  
 55:     txtKQ.setText(String.valueOf(kq));
 56:   }
 57: 
 58:   public void paint(Graphics g) {
 59:     g.setFont(new Font("Tahoma", 1, 14));  
 60:     g.drawString("CONG - TRU - NHAN - CHIA", 30, 20 );    
 61:   }
 62: }

Không có nhận xét nào: