hola a todoslaneros.....estoy en un proyecto...quiero hacer una calculadora.......ya hice los botones, y el TextField que deberia etar...despues le he agregado el action listener............pero ahi es el problema........no se como hacer...para que ingrese el numero y al apretar cualquiera de los botones "+""-"o los demas.......deje ingresar un nuevo numero...........en el mismo TextField....y resuelva la operacion indicada con el numero anterior...alguien me podria yudar por favor......¿debo poner otro evento aparte de actionlistener????
Si vas a ser tecnico en el programa, deberias poner un escucha por cada boton y asignarle un metodo que gestione el evento...pero bueno lo que sea que te diga es pura carreta....mejor aqui va un code para que te ilustres mejor...PAZ Y SUERTE.
PHP:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Scalc extends JFrame implements KeyListener
{
static String sn[] = new String[2]; //String de datos
static double res = 0, ans = 0; // Variables numericas globales
static int cop = 0, op = 0, est = 0, pto = 0; //Variable de control
static JButton b0 = new JButton("0");//Elementos del entorno.
static JButton b1 = new JButton("1");
static JButton b2 = new JButton("2");
static JButton b3 = new JButton("3");
static JButton b4 = new JButton("4");
static JButton b5 = new JButton("5");
static JButton b6 = new JButton("6");
static JButton b7 = new JButton("7");
static JButton b8 = new JButton("8");
static JButton b9 = new JButton("9");
static JButton bs = new JButton("+");
static JButton br = new JButton("-");
static JButton bm = new JButton("*");
static JButton bd = new JButton("/");
static JButton ba = new JButton("Ac");
static JButton bc = new JButton("C");
static JButton bx = new JButton("=");
static JButton bn = new JButton("Ans");
static JButton bp = new JButton(".");
static JTextField tnum = new JTextField();
static JTextField tans = new JTextField();
static JLabel lnum = new JLabel("N#:");
static JLabel lans = new JLabel("Ans");
static JPanel p = new JPanel();
public static void main(String args[])//Metodo principal de arranque.
{
sn[0]="";//Se inicializan las variables de datos en bacio
sn[1]="";
new Scalc();//Se invoca el constructor del objeto
}
public Scalc()//Constructor del objeto
{
this.addKeyListener(this);//Se agrega la interfaz Key listener al objeto.
this.addWindowListener(new WindowAdapter() {public void windowClosing( WindowEvent evt ) {System.exit(0);}});//Se define el metodo para cerrar la ventana
lans.setBounds(10, 10, 30, 20);//Define pocicion y tamaño del objeto
lans.setVisible(true);//Se hace visible el objeto
lans.addKeyListener(this);
tans.setBounds(50, 10, 250, 20);
tans.setEditable(false);//Se hace ineditable el contenido del objeto
tans.setBackground(Color.white);//Define color de fondo
tans.setVisible(true);
tans.addKeyListener(this);
lnum.setBounds(10, 40, 30, 20);
lnum.setVisible(true);
lnum.addKeyListener(this);
tnum.setBounds(50, 40, 250, 20);
tnum.setEditable(false);
tnum.setBackground(Color.white);
tnum.setVisible(true);
tnum.addKeyListener(this);
b7.setBounds(10, 70, 50, 50);
b7.setVisible(true);
b7.addKeyListener(this);
b8.setBounds(70, 70, 50, 50);
b8.setVisible(true);
b8.addKeyListener(this);
b9.setBounds(130, 70, 50, 50);
b9.setVisible(true);
b9.addKeyListener(this);
b4.setBounds(10, 130, 50, 50);
b4.setVisible(true);
b4.addKeyListener(this);
b5.setBounds(70, 130, 50, 50);
b5.setVisible(true);
b5.addKeyListener(this);
b6.setBounds(130, 130, 50, 50);
b6.setVisible(true);
b6.addKeyListener(this);
b1.setBounds(10, 190, 50, 50);
b1.setVisible(true);
b1.addKeyListener(this);
b2.setBounds(70, 190, 50, 50);
b2.setVisible(true);
b2.addKeyListener(this);
b3.setBounds(130, 190, 50, 50);
b3.setVisible(true);
b3.addKeyListener(this);
b0.setBounds(10, 250, 50, 50);
b0.setVisible(true);
b0.addKeyListener(this);
bp.setBounds(70, 250, 50, 50);
bp.setVisible(true);
bp.addKeyListener(this);
bx.setBounds(130, 250, 50, 50);
bx.setVisible(true);
bx.addKeyListener(this);
bn.setBounds(190, 250, 110, 50);
bn.setVisible(true);
bn.addKeyListener(this);
bs.setBounds(190, 70, 50, 50);
bs.setVisible(true);
bs.addKeyListener(this);
br.setBounds(250, 70, 50, 50);
br.setVisible(true);
br.addKeyListener(this);
bm.setBounds(190, 130, 50, 50);
bm.setVisible(true);
bm.addKeyListener(this);
bd.setBounds(250, 130, 50, 50);
bd.setVisible(true);
bd.addKeyListener(this);
ba.setBounds(190, 190, 50, 50);
ba.setVisible(true);
ba.addKeyListener(this);
bc.setBounds(250, 190, 50, 50);
bc.setVisible(true);
bc.addKeyListener(this);
p.addKeyListener(this);
b0.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(48);}});// Se invoca el metodo deco() y se le pasa como argumento el key code 48 = key 0
b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(49);}});//49 = key 1
b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(50);}});//...
b3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(51);}});//....
b4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(52);}});
b5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(53);}});
b6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(54);}});
b7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(55);}});
b8.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(56);}});
b9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(57);}});
bp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(46);}});//46 = key . "Punto"
bs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(83);}});//83 = key s suma
br.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(82);}});//82 = key r resta
bm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(77);}});//77 = key m multiplica
bd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(68);}});//68 = key d divide
bx.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(10);}});//10 = key "enter" ejecuta
bn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(78);}});//78 = key n funcion "Ans"
ba.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(65);}});//65 = Key a funcion "Ac"
bc.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){deco(67);}});//67 = key c funcion "C"
//Se añaden los elementos a la ventana.
this.add(lans);
this.add(tans);
this.add(lnum);
this.add(tnum);
this.add(b7);
this.add(b8);
this.add(b9);
this.add(b4);
this.add(b5);
this.add(b6);
this.add(b1);
this.add(b2);
this.add(b3);
this.add(b0);
this.add(bp);
this.add(bn);
this.add(bs);
this.add(br);
this.add(bm);
this.add(bd);
this.add(bx);
this.add(ba);
this.add(bc);
this.add(p);
this.setTitle("Scalc 1.0");//Titulo de la ventana
this.setResizable(false);//Se hace la ventana de tamaño fijo
this.setBounds(200, 200, 315, 340);//posicion y tamaño de la ventana
this.setVisible(true);//Ventana visible
}
//Metodos de KeyListener, deben aplicarse para operar la calculadora por teclado.
public void keyPressed(KeyEvent e)//Captura las teclas pulsadas
{
int tec = e.getKeyCode();//Obtiene el key code de la tecla pulsada
deco(tec);//Invoca el metodod deco y le pasa como parametro el keycode
}
public void keyReleased(KeyEvent e)
{
//Metodo de KeyListener
}
public void keyTyped(KeyEvent e)
{
//Metodo de KeyListener
}
//Metodo para invocar funciones y controlar datos
public void deco(int tec)
{
if(tec <= 57 && tec >= 48)//Para las teclas 0,1,....9
{
tec = tec-48; //Reduce el keycode en 48 para obtener el valor real
sn[cop]= new String(sn[cop]+tec);//Añade el caracter de la tecla al string de datos actual.
tnum.setText(sn[cop]);//Visualiza el String de datos actual
}
else if(tec == 46)//Para la tecla punto.
{
if(pto == 0)//Solo si no se ha usado la funsion punto
{
pto = 1;//Desactiva a funsion punto.
sn[cop]= new String(sn[cop]+".");
tnum.setText(sn[cop]);
}
}
else if(tec == 83)//Funcion suma
{
pto = 0;//Reactiva la funsion punto
tnum.setText("+");//Muestra el signo de la operacion
if(est == 1)//Si esta en modo cadena 1 ejecuta la ultima orden programada
run(); //invoca ejecucion
est = 1;//Fija el modo cadena
cop = 1;//Pasa al segundo String de datos
op = 1;//Fija el operador en 1 -> 1 = suma 2 = resta 3 = multiplica 4 = divide
}
else if(tec == 82)//Funcion resta
{
pto = 0;
tnum.setText("-");
if(est == 1)
run();
est = 1;
cop = 1;
op = 2;
}
else if(tec == 77)//Funcion multiplica
{
pto = 0;
tnum.setText("*");
if(est == 1)
run();
est = 1;
cop = 1;
op = 3;
}
else if(tec == 68)//Funcion divide
{
pto = 0;
tnum.setText("/");
if(est == 1)
run();
est = 1;
cop = 1;
op = 4;
}
else if(tec == 65)//Fucion Ac
{
pto = 0;
cop = 0;//Devuelve al primer String de datos
op = 0;//Fija el operador en nulo
res = 0;//Fija el resultado en 0
sn[0]="";//Limpia los Strings de datos
sn[1]="";
tnum.setText("");//Limpia la ventana N#
}
else if(tec == 67)//Funcion C
{
pto = 0;
op = 0;//Fiaja el operador a nulo
sn[cop]="";//Limpia el Strin de datos actual
tnum.setText("");//Limpia la ventan N#
}
else if(tec == 78)//Funcion Ans
{
sn[cop] = new String(""+ans);//Carga el String de datos actual con la ultima respuesta final
tnum.setText(sn[cop]);//Visualiza el Ans
cop = 1;//Pasa al segundo stgring de datos
}
else if(tec == 10)//Funcion = "Exe"
{
run();//Invoca ejecucion
ans = res; //Almacena en carga el ans con el resultado de la operacion
tans.setText(sn[0]);//Visualiza el Ans
est = 0;//Apaga el modo cadena
pto = 0;
}
}
public void run()//Metodo de ejecucion general
{
if(op == 1)//Suma
{
res = (Double.valueOf(sn[0]).doubleValue())+(Double.valueOf(sn[1]).doubleValue());//Extrae el valor numerico de los Strings de datos y opera
sn[0] = new String(""+res);//Caraca la respuesta en el primer String de datos para habilitar el modo cadena
tnum.setText(sn[0]);//Visualiza respuesta en la ventana
}
else if(op == 2)
{
res = (Double.valueOf(sn[0]).doubleValue())-(Double.valueOf(sn[1]).doubleValue());
sn[0] = new String(""+res);
tnum.setText(sn[0]);
}
else if(op == 3)
{
res = (Double.valueOf(sn[0]).doubleValue())*(Double.valueOf(sn[1]).doubleValue());
sn[0] = new String(""+res);
tnum.setText(sn[0]);
}
else if(op == 4)
{
double q = (Double.valueOf(sn[1]).doubleValue());//Extrae el valor del segundo miembro
if(q == 0)//Si el divisor es 0
{
sn[0] = new String(""+0);//Fija a 0 el primer String de datos
tnum.setText("0 Operacion Indeterminada Math Error");//Envia mensaje de error
}
else
{
res = (Double.valueOf(sn[0]).doubleValue())/(Double.valueOf(sn[1]).doubleValue());
sn[0] = new String(""+res);
tnum.setText(sn[0]);
}
}
sn[cop] = "";//Limpia el String de datos actual
}
}
PSDT: El KeyListener es para manejar la calculadora con el teclado, pero es opcional no influye en su funcionamiento....