You are on page 1of 3

package ALDOCALCULAR;

import
import
import
import
import
import
import
import
import
import
import
import
public
istener {

java.awt.BorderLayout;
java.awt.Color;
java.awt.GridLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.KeyEvent;
java.awt.event.KeyListener;
javax.swing.JApplet;
javax.swing.JButton;
javax.swing.JPanel;
javax.swing.JTextField;
javax.swing.SwingConstants;
class ALDOCALCULAR extends JApplet implements ActionListener,KeyL
private
private
private
private

JTextField t=null;
int oper1=0;
int oper2=0;
String command=null;

private boolean sw=true;


public ALDOCALCULAR() {
this.getContentPane().setLayout(new BorderLayout()) ;
t=new JTextField(0);
t.setBackground(Color.yellow);
t.setHorizontalAlignment(SwingConstants.RIGHT);
t.addKeyListener(this);
JPanel aux=new JPanel();
aux.setLayout(new GridLayout(3,4));
JButton b=null;
b= new JButton("1");
b.addActionListener(this);
aux.add(b);
b= new JButton("2");
b.addActionListener(this);
aux.add(b);
b= new JButton("3");
b.addActionListener(this);
aux.add(b);
b= new JButton("+");
b.addActionListener(this);
aux.add(b);
b= new JButton("4");
b.addActionListener(this);
aux.add(b);
b= new JButton("5");
b.addActionListener(this);
aux.add(b);
b= new JButton("6");
b.addActionListener(this);
aux.add(b);
b= new JButton("-");
b.addActionListener(this);
aux.add(b);
b= new JButton("7");
b.addActionListener(this);
aux.add(b);

b= new JButton("8");
b.addActionListener(this);
aux.add(b);
b= new JButton("9");
b.addActionListener(this);
aux.add(b);
b= new JButton("=");
b.addActionListener(this);
aux.add(b);
this.getContentPane().add(t,BorderLayout.NORTH);
this.getContentPane().add(aux,BorderLayout.CENTER);
}
//Se ha producido un ActionEvent
public void actionPerformed(ActionEvent ev){
String aux=((JButton)ev.getSource()).getText();
if(aux.equals("+")||aux.equals("-")) {
command=aux;
oper1=Integer.parseInt(t.getText());
sw=true;}
else if(aux.equals("=")) {
oper2=Integer.parseInt(t.getText());
if(command.equals("+")) {
t.setText(new Integer(oper1+oper2).toStr
ing());
oper1=oper1+oper2;
// permite tecle
ar un numero y ="(repitiendo el ultimo operador)
}
else {
t.setText(new Integer(oper1-oper2).toStr
ing());
oper1=oper1-oper2;
// permite tecle
ar un numero y "="(repitiendo el ultimo
operador)
}
sw=true;
}
else {
if(sw) {
t.setText(aux);
sw=false;
}
else
t.setText(t.getText()+ aux);}}
//Se ha producido un KeyEvent de tipo keyPressed
public void keyPressed(KeyEvent ev){
}
//Se ha producido un KeyEvent de tipo keyReleased
public void keyReleased(KeyEvent ev){
char tmp=ev.getKeyChar();
if(!Character.isDigit(tmp)){
t.setText(t.getText().substring(0,t.getT
ext().length()-1));
t.setCaretPosition(t.getText().length())
;
}
}

//Se ha producido un KeyEvent de tipo keyTyped


public void keyTyped(KeyEvent ev){
}
}

You might also like