En este Articulo realizaremos una Aplicacion en Java desde cero, se trata de un proyecto muy comun y recurrente en tareas escolares 😉 hablamos de Como Hacer una Calculadora en Java paso a paso sin ayuda de asistentes graficos que te generen la Interfaz. Si bien los Asistentes te ayudan mucho y te ahorran tiempo valioso que puedes invertir en otros aspectos de tu App en este Tutorial lo que queremos es aprender a programar y que mejor que hacerlo escribiendo el codigo limpio y puro que entendamos completamente ( en ocaciones los asistentes graficos te generan mucho codigo basura 😕 ). Asi que vamos ya al Tuto..
Hoy veremos
Comenzamos …
Recientemente un amigo me pidio ayuda para realizar este proyecto como una tarea en su Escuela y me vino a la cabeza como los mismos trabajos son pedidos una y otra vez 😀 asi es que esa es la razon que me motivo a realizar este mini tuto. Aclarar que estoy programando con Netbeans ( mas por costumbre 😀 ) pero no es para nada necesario, como te digo no haremos uso de ningun asistente grafico solo escribire el codigo ahi y compilare.. tu puedes usar otro IDE, el notepad o hasta el block de notas 😀 solo necesitarias un compilador.
La estructura base de este proyecto #calculadoraenjava es este ..

En el paquete jmr.blog.res tengo una imagen png que sera el icono de la calculadora y es de 20×20, el codigo de la clase Ventana es el siguiente:

¿Necesitas aprender algo nuevo ? Ve a Udemy, busca el tema del que quieres aprender, selecciona el curso para ti y continua con tu aprendizaje.
Udemy 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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(); //HACEMOS VISIBLE LA APP setVisible(true); } private void init() { //INTERFAZ Y FUNCIONALIDAD } public static void main(String args[]){ //CREAMOS UN NUEVO OBJETO VENTANA new Ventana(); } } |
que al ejecutar tendremos simplemente un cascaron de la calculadora 😀

Ahora si manos a la obra..
El Diseño, Paneles y Layouts
Necesitamos ahora declarar 3 variables.
1 2 3 4 5 | JPanel panel_principal; JPanel panel_botones; JTextField caja; |
El panel Principal con un layout ( borderLayout ) en el que puedes agregar elementos al norte sur este u oeste que contendra al norte una caja de Texto ( JTextField ) y al centro un panel con los botones de la calculadora ( JPanel ).
Ahora el metodo init lucira asi
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | private void init() { //INTERFAZ Y FUNCIONALIDAD //CREAMOS PANEL PRINCIPAL CON LAYOUT BORDERLAYOUT panel_principal = new JPanel(); panel_principal.setLayout(new BorderLayout()); //EN EL NORTE IRA LA CAJA DE TEXTO caja = new JTextField(); panel_principal.add("North",caja); //EN EL CENTRO IRA EL PANEL DE BOTONES panel_botones = new JPanel(); //El GRIDLAYOUT RECIBE COMO PARAMETROS: //FILAS,COLUMNAS ESPACIADO ENTRE FILAS, //ESPACIADO ENTRE COLUMNAS panel_botones.setLayout(new GridLayout(5,4,8,8)); //agregarBotones(); panel_principal.add("Center",panel_botones); //AGREGAMOS TODO EL CONTENIDO QUE ACABAMOS DE HACER EN //PANEL_PRINCIPAL A EL PANEL DEL FORMULARIO getContentPane().add(panel_principal); } |
Como puedes ver todo esta comentado para que no te pierdas con su funcion, si te fijas tambien, el metodo agregarBotones esta comentado ( // ), esto es porque en este metodo agregaremos mas adelante los botones de la interfaz de nuestra calculadora, si ejecutamos lucira asi:

Ahora vamos a agregar codigo al metodo agregarBotones() 😀
Agregando los Botones y sus Respectivos Eventos
Simplemente escribimos el codigo para agregar botones en el metodo agregarBotones() ( recuerda descomentarlo 😀 ), pero antes declaramos algunas variables nuevas:
1 2 3 4 5 6 | JButton boton[]; double op1=0,op2=0; String operacion=""; boolean nueva=true; |
Un arreglos de botones, dos variables double para almacenar los valores de cada operacion de suma, resta, multiplicacion o division, una cadena de texto para almacenar el tipo de operacion que estamos realizando y una variable llamada «nueva» que indicara cuando se inicie una nueva operacion y asi borrar pantalla.
El codigo del metodo agregarBotones ( no te asustes si es un poco largo 😀 es bastante repetitivo ) es el siguiente:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | private void agregarBotones() { //INICIALIZAMOS EL ARREGLO DE BOTONES boton = new JButton[20]; //INICIALIZAMOS LOS 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("+"); //AGREAMOS LOS BOTONES AL 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){} } }); //NUMEROS Y 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=""; } }); } |
y al ejecutar ya tenemos nuestra calculadora armada y funcionando 😉

37 Comentarios