SlideShare a Scribd company logo
1 of 7
¿Cómo hacer una calculadora en Java y en Visual Basic?
En Java:
Para crear la interfaz de la calculadora vacía.
package jmr.blog;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Ventana extends JFrame{
public Ventana(){
//TITULO
setTitle("Calculadora JMR");
//TAMAÑO
setSize(250,300);
//DIMENSIONABLE O NO
setResizable(false);
//LOCACION
setLocationRelativeTo(null);
//SALIR AL CLICKEAR LA CRUZ
setDefaultCloseOperation(EXIT_ON_CLOSE);
//ICONO DE LA CALCULADORA
setIconImage(new ImageIcon(getClass().getResource("/jmr/blog/res/favicon.png")).getImage());
//METODO PARA CREAR INTERFAZ Y AGREGAR EVENTOS A BOTONES
init();
//HACEMOSVISIBLE LA APP
setVisible(true);
}
privatevoid init() {
//INTERFAZ Y FUNCIONALIDAD
}
public staticvoid main(String args[]){
//CREAMOS UN NUEVO OBJETO VENTANA
new Ventana();
}
}
Quedará así:
Ahora para agregar el diseño, paneles y layouts.
Este código es para agregar una caja de texto:
JPanel panel_principal;
JPanel panel_botones;
JTextField caja;
Para agregar el panel de botones:
privatevoid init() {
//INTERFAZ Y FUNCIONALIDAD
//CREAMOS PANELPRINCIPALCON LAYOUT BORDERLAYOUT
panel_principal = new JPanel();
panel_principal.setLayout(new BorderLayout());
//EN EL NORTEIRA LA CAJA DE TEXTO
caja = new JTextField();
panel_principal.add("North",caja);
//EN EL CENTRO IRA EL PANELDE BOTONES
panel_botones = new JPanel();
//El GRIDLAYOUT RECIBE COMO PARAMETROS:
//FILAS,COLUMNASESPACIADO ENTREFILAS,
//ESPACIADO ENTRE COLUMNAS
panel_botones.setLayout(new GridLayout(5,4,8,8));
//agregarBotones();
panel_principal.add("Center",panel_botones);
//AGREGAMOSTODO EL CONTENIDO QUEACABAMOSDEHACER EN
//PANEL_PRINCIPAL A EL PANELDEL FORMULARIO
getContentPane().add(panel_principal);
}
Quedará así:
Para agregar botones en el panel de botones:
JButton boton[];
double op1=0,op2=0;
String operacion="";
boolean nueva=true;
Este código es para agregar la suma, resta, multiplicar etcétera y almacernarlo.
privatevoid agregarBotones() {
//INICIALIZAMOSEL ARREGLO DE BOTONES
boton = new JButton[20];
//INICIALIZAMOSLOS BOTONES
boton[0]=new JButton("CE");
boton[1]=new JButton("");
boton[2]=new JButton("");
boton[3]=new JButton("");
boton[4]=new JButton("7");
boton[5]=new JButton("8");
boton[6]=new JButton("9");
boton[7]=new JButton("/");
boton[8]=new JButton("4");
boton[9]=new JButton("5");
boton[10]=new JButton("6");
boton[11]=new JButton("*");
boton[12]=new JButton("1");
boton[13]=new JButton("2");
boton[14]=new JButton("3");
boton[15]=new JButton("-");
boton[16]=new JButton("0");
boton[17]=new JButton(".");
boton[18]=new JButton("=");
boton[19]=new JButton("+");
//AGREAMOSLOS BOTONESAL PANEL BOTONES
for(int i=0;i<20;i++){
panel_botones.add(boton[i]);
}
//EVENTOS DE LOS BOTONES
//OPERACIONES
boton[19].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
try{
if(op1!=0)
op1=op1+Double.parseDouble(caja.getText());
else
op1=Double.parseDouble(caja.getText());
operacion="suma";
caja.setText("");
}catch(Exception err){}
}
});
boton[15].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
try{
if(op1!=0)
op1=op1-Double.parseDouble(caja.getText());
else
op1=Double.parseDouble(caja.getText());
operacion="resta";
caja.setText("");
}catch(Exception err){}
}
});
boton[11].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
try{
if(op1!=0)
op1=op1*Double.parseDouble(caja.getText());
else
op1=Double.parseDouble(caja.getText());
operacion="multiplicacion";
caja.setText("");
}catch(Exception err){}
}
});
boton[7].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
try{
if(op1!=0)
op1=op1/Double.parseDouble(caja.getText());
else
op1=Double.parseDouble(caja.getText());
operacion="division";
caja.setText("");
}catch(Exception err){}
}
});
//NUMEROSY PUNTO DECIMAL
boton[4].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"7");
}
});
boton[5].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"8");
}
});
boton[6].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"9");
}
});
boton[8].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"4");
}
});
boton[9].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"5");
}
});
boton[10].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"6");
}
});
boton[12].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"1");
}
});
boton[13].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"2");
}
});
boton[14].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"3");
}
});
boton[16].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+"0");
}
});
boton[17].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
if(nueva){caja.setText("");nueva=false;}
caja.setText(caja.getText()+".");
}
});
//IGUAL
boton[18].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
try{
op2=Double.parseDouble(caja.getText());
}catch(Exception err){}
if(operacion.equals("suma")){
double res=op1+op2;
caja.setText(String.valueOf(res));
op1=op2=0;
operacion="";
}else if(operacion.equals("resta")){
double res=op1-op2;
caja.setText(String.valueOf(res));
op1=op2=0;
operacion="";
}else if(operacion.equals("multiplicacion")){
double res=op1*op2;
caja.setText(String.valueOf(res));
op1=op2=0;
operacion="";
}else if(operacion.equals("division")){
double res=op1/op2;
caja.setText(String.valueOf(res));
op1=op2=0;
operacion="";
}
nueva=true;
}
});
//CE
boton[0].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
caja.setText("");
op1=op2=0;
operacion="";
}
});
}
En Visual Basic:
Hay que crear una caja de texto, una matriz de diez botes de comando para
número, otra matriz de cuatro botones de comando para (+,-,/,*), un comando para
nueva operación y un comando para el resultado.
Private SubIgual_Click()
Select Case signo 'la variable signo te dice si sumas(0) si restas(1)......
Case 0
Text1.Text = suma(anterior,Val(Text1.Text))'llamada a la función suma
Case 1
Text1.Text = resta(anterior, Val(Text1.Text))
Case 2
Text1.Text = multiplicar(anterior, Val(Text1.Text))
Case 3
Text1.Text = Dividir(anterior, Val(Text1.Text))
EndSelect
EndSub
Private SubNueva_Click()
Text1.Text = ""
EndSub
Private SubOperador_Click(Index As Integer)
signo = Index 'si index es 0 sumas, si es 1 restas......
anterior= Val(Text1.Text)
Text1.Text = ""
EndSub
Private SubNumero_Click(IndexAs Integer)
Text1.Text = Text1.Text + Numero(Index).Caption
EndSub
Private Functionsuma(Numero As Integer, Operador As Integer) As Integer
suma = Numero + Operador
EndFunction
Private Functionresta(NumeroAs Integer,OperadorAs Integer)As Integer
resta = Numero - Operador
EndFunction
Private Functionmultiplicar(NumeroAs Integer, Operador As Integer) As Integer
multiplicar = Numero* Operador
EndFunction
Private FunctionDividir(NumeroAs Integer, Operador As Integer) As Integer
Dividir = Numero / Operador
EndFunction
Private SubSalir_Click()
UnloadMe
EndSub

More Related Content

What's hot

Aller plus loin avec Doctrine2
Aller plus loin avec Doctrine2Aller plus loin avec Doctrine2
Aller plus loin avec Doctrine2André Tapia
 
A slew of AACM 50th anniversary celebrations this weekend
A slew of AACM 50th anniversary celebrations this weekendA slew of AACM 50th anniversary celebrations this weekend
A slew of AACM 50th anniversary celebrations this weekendchicagonewsyesterday
 
Semana 12 interfaces gráficas de usuario
Semana 12   interfaces gráficas de usuarioSemana 12   interfaces gráficas de usuario
Semana 12 interfaces gráficas de usuarioTerryJoss
 
Como hacer una calculadora en java
Como hacer una calculadora en javaComo hacer una calculadora en java
Como hacer una calculadora en javaaldair fernandez
 
Jak zabít několik much jednou ranou přechodem na fragmenty
Jak zabít několik much jednou ranou přechodem na fragmentyJak zabít několik much jednou ranou přechodem na fragmenty
Jak zabít několik much jednou ranou přechodem na fragmentyDavid Vávra
 
Pianist and composer Jeff Kowalkowski releases strong new trio album
Pianist and composer Jeff Kowalkowski releases strong new trio albumPianist and composer Jeff Kowalkowski releases strong new trio album
Pianist and composer Jeff Kowalkowski releases strong new trio albumirwinvifxcfesre
 
聞いてスッキリ!Lightningの理解ポイント
聞いてスッキリ!Lightningの理解ポイント聞いてスッキリ!Lightningの理解ポイント
聞いてスッキリ!Lightningの理解ポイント寛 吉田
 
UISearchController par Stéphane sudre
UISearchController par Stéphane sudreUISearchController par Stéphane sudre
UISearchController par Stéphane sudreCocoaHeads France
 
Simular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariaSimular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariajbersosa
 
Project Komputer Grafik
Project Komputer GrafikProject Komputer Grafik
Project Komputer GrafikHamimSuyuti
 
Here's the Downtown Sound lineup for 2015
Here's the Downtown Sound lineup for 2015Here's the Downtown Sound lineup for 2015
Here's the Downtown Sound lineup for 2015chicagonewsyesterday
 
jQuery sans jQuery
jQuery sans jQueryjQuery sans jQuery
jQuery sans jQuerygoldoraf
 

What's hot (20)

Proyecto Final Android-SQLite
Proyecto Final Android-SQLiteProyecto Final Android-SQLite
Proyecto Final Android-SQLite
 
Aller plus loin avec Doctrine2
Aller plus loin avec Doctrine2Aller plus loin avec Doctrine2
Aller plus loin avec Doctrine2
 
A slew of AACM 50th anniversary celebrations this weekend
A slew of AACM 50th anniversary celebrations this weekendA slew of AACM 50th anniversary celebrations this weekend
A slew of AACM 50th anniversary celebrations this weekend
 
Semana 12 interfaces gráficas de usuario
Semana 12   interfaces gráficas de usuarioSemana 12   interfaces gráficas de usuario
Semana 12 interfaces gráficas de usuario
 
Stack Linier 2
Stack Linier 2Stack Linier 2
Stack Linier 2
 
Sbaw091013
Sbaw091013Sbaw091013
Sbaw091013
 
Como hacer una calculadora en java
Como hacer una calculadora en javaComo hacer una calculadora en java
Como hacer una calculadora en java
 
Best Fried Chicken
Best Fried ChickenBest Fried Chicken
Best Fried Chicken
 
Tugas praktek modul isbd
Tugas praktek modul isbdTugas praktek modul isbd
Tugas praktek modul isbd
 
Jak zabít několik much jednou ranou přechodem na fragmenty
Jak zabít několik much jednou ranou přechodem na fragmentyJak zabít několik much jednou ranou přechodem na fragmenty
Jak zabít několik much jednou ranou přechodem na fragmenty
 
Pianist and composer Jeff Kowalkowski releases strong new trio album
Pianist and composer Jeff Kowalkowski releases strong new trio albumPianist and composer Jeff Kowalkowski releases strong new trio album
Pianist and composer Jeff Kowalkowski releases strong new trio album
 
聞いてスッキリ!Lightningの理解ポイント
聞いてスッキリ!Lightningの理解ポイント聞いてスッキリ!Lightningの理解ポイント
聞いてスッキリ!Lightningの理解ポイント
 
Cerveza programa
Cerveza programaCerveza programa
Cerveza programa
 
Java
JavaJava
Java
 
UISearchController par Stéphane sudre
UISearchController par Stéphane sudreUISearchController par Stéphane sudre
UISearchController par Stéphane sudre
 
Simular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentariaSimular un next del recordset en php de forma rudimentaria
Simular un next del recordset en php de forma rudimentaria
 
Blog 4
Blog 4Blog 4
Blog 4
 
Project Komputer Grafik
Project Komputer GrafikProject Komputer Grafik
Project Komputer Grafik
 
Here's the Downtown Sound lineup for 2015
Here's the Downtown Sound lineup for 2015Here's the Downtown Sound lineup for 2015
Here's the Downtown Sound lineup for 2015
 
jQuery sans jQuery
jQuery sans jQueryjQuery sans jQuery
jQuery sans jQuery
 

Hacer una calculadora en Java y en Visual Basic

  • 1. ¿Cómo hacer una calculadora en Java y en Visual Basic? En Java: Para crear la interfaz de la calculadora vacía. package jmr.blog; import javax.swing.ImageIcon; import javax.swing.JFrame; public class Ventana extends JFrame{ public Ventana(){ //TITULO setTitle("Calculadora JMR"); //TAMAÑO setSize(250,300); //DIMENSIONABLE O NO setResizable(false); //LOCACION setLocationRelativeTo(null); //SALIR AL CLICKEAR LA CRUZ setDefaultCloseOperation(EXIT_ON_CLOSE); //ICONO DE LA CALCULADORA setIconImage(new ImageIcon(getClass().getResource("/jmr/blog/res/favicon.png")).getImage()); //METODO PARA CREAR INTERFAZ Y AGREGAR EVENTOS A BOTONES init(); //HACEMOSVISIBLE LA APP setVisible(true); } privatevoid init() { //INTERFAZ Y FUNCIONALIDAD } public staticvoid main(String args[]){ //CREAMOS UN NUEVO OBJETO VENTANA new Ventana(); } } Quedará así:
  • 2. Ahora para agregar el diseño, paneles y layouts. Este código es para agregar una caja de texto: JPanel panel_principal; JPanel panel_botones; JTextField caja; Para agregar el panel de botones: privatevoid init() { //INTERFAZ Y FUNCIONALIDAD //CREAMOS PANELPRINCIPALCON LAYOUT BORDERLAYOUT panel_principal = new JPanel(); panel_principal.setLayout(new BorderLayout()); //EN EL NORTEIRA LA CAJA DE TEXTO caja = new JTextField(); panel_principal.add("North",caja); //EN EL CENTRO IRA EL PANELDE BOTONES panel_botones = new JPanel(); //El GRIDLAYOUT RECIBE COMO PARAMETROS: //FILAS,COLUMNASESPACIADO ENTREFILAS, //ESPACIADO ENTRE COLUMNAS panel_botones.setLayout(new GridLayout(5,4,8,8)); //agregarBotones(); panel_principal.add("Center",panel_botones); //AGREGAMOSTODO EL CONTENIDO QUEACABAMOSDEHACER EN //PANEL_PRINCIPAL A EL PANELDEL FORMULARIO getContentPane().add(panel_principal); } Quedará así: Para agregar botones en el panel de botones: JButton boton[]; double op1=0,op2=0; String operacion=""; boolean nueva=true;
  • 3. Este código es para agregar la suma, resta, multiplicar etcétera y almacernarlo. privatevoid agregarBotones() { //INICIALIZAMOSEL ARREGLO DE BOTONES boton = new JButton[20]; //INICIALIZAMOSLOS BOTONES boton[0]=new JButton("CE"); boton[1]=new JButton(""); boton[2]=new JButton(""); boton[3]=new JButton(""); boton[4]=new JButton("7"); boton[5]=new JButton("8"); boton[6]=new JButton("9"); boton[7]=new JButton("/"); boton[8]=new JButton("4"); boton[9]=new JButton("5"); boton[10]=new JButton("6"); boton[11]=new JButton("*"); boton[12]=new JButton("1"); boton[13]=new JButton("2"); boton[14]=new JButton("3"); boton[15]=new JButton("-"); boton[16]=new JButton("0"); boton[17]=new JButton("."); boton[18]=new JButton("="); boton[19]=new JButton("+"); //AGREAMOSLOS BOTONESAL PANEL BOTONES for(int i=0;i<20;i++){ panel_botones.add(boton[i]); } //EVENTOS DE LOS BOTONES //OPERACIONES boton[19].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ try{ if(op1!=0) op1=op1+Double.parseDouble(caja.getText()); else op1=Double.parseDouble(caja.getText()); operacion="suma"; caja.setText(""); }catch(Exception err){} } }); boton[15].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ try{ if(op1!=0) op1=op1-Double.parseDouble(caja.getText()); else op1=Double.parseDouble(caja.getText()); operacion="resta"; caja.setText(""); }catch(Exception err){} } }); boton[11].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ try{
  • 4. if(op1!=0) op1=op1*Double.parseDouble(caja.getText()); else op1=Double.parseDouble(caja.getText()); operacion="multiplicacion"; caja.setText(""); }catch(Exception err){} } }); boton[7].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ try{ if(op1!=0) op1=op1/Double.parseDouble(caja.getText()); else op1=Double.parseDouble(caja.getText()); operacion="division"; caja.setText(""); }catch(Exception err){} } }); //NUMEROSY PUNTO DECIMAL boton[4].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"7"); } }); boton[5].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"8"); } }); boton[6].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"9"); } }); boton[8].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"4"); } }); boton[9].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"5"); } }); boton[10].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;}
  • 5. caja.setText(caja.getText()+"6"); } }); boton[12].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"1"); } }); boton[13].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"2"); } }); boton[14].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"3"); } }); boton[16].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"0"); } }); boton[17].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ if(nueva){caja.setText("");nueva=false;} caja.setText(caja.getText()+"."); } }); //IGUAL boton[18].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ try{ op2=Double.parseDouble(caja.getText()); }catch(Exception err){} if(operacion.equals("suma")){ double res=op1+op2; caja.setText(String.valueOf(res)); op1=op2=0; operacion=""; }else if(operacion.equals("resta")){ double res=op1-op2; caja.setText(String.valueOf(res)); op1=op2=0; operacion=""; }else if(operacion.equals("multiplicacion")){ double res=op1*op2; caja.setText(String.valueOf(res)); op1=op2=0; operacion=""; }else if(operacion.equals("division")){ double res=op1/op2;
  • 6. caja.setText(String.valueOf(res)); op1=op2=0; operacion=""; } nueva=true; } }); //CE boton[0].addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt){ caja.setText(""); op1=op2=0; operacion=""; } }); } En Visual Basic: Hay que crear una caja de texto, una matriz de diez botes de comando para número, otra matriz de cuatro botones de comando para (+,-,/,*), un comando para nueva operación y un comando para el resultado. Private SubIgual_Click() Select Case signo 'la variable signo te dice si sumas(0) si restas(1)...... Case 0 Text1.Text = suma(anterior,Val(Text1.Text))'llamada a la función suma Case 1 Text1.Text = resta(anterior, Val(Text1.Text)) Case 2 Text1.Text = multiplicar(anterior, Val(Text1.Text)) Case 3 Text1.Text = Dividir(anterior, Val(Text1.Text)) EndSelect EndSub Private SubNueva_Click() Text1.Text = "" EndSub Private SubOperador_Click(Index As Integer) signo = Index 'si index es 0 sumas, si es 1 restas...... anterior= Val(Text1.Text) Text1.Text = "" EndSub Private SubNumero_Click(IndexAs Integer) Text1.Text = Text1.Text + Numero(Index).Caption EndSub Private Functionsuma(Numero As Integer, Operador As Integer) As Integer suma = Numero + Operador EndFunction
  • 7. Private Functionresta(NumeroAs Integer,OperadorAs Integer)As Integer resta = Numero - Operador EndFunction Private Functionmultiplicar(NumeroAs Integer, Operador As Integer) As Integer multiplicar = Numero* Operador EndFunction Private FunctionDividir(NumeroAs Integer, Operador As Integer) As Integer Dividir = Numero / Operador EndFunction Private SubSalir_Click() UnloadMe EndSub