SlideShare a Scribd company logo
En esta práctica vamos a crear una sencilla calculadora utilizando el framework AWT (Abstract Window Toolkit) de Java.
Etiquetas: Frame, Panel, paquete AWT, Gestión de eventos, Notificador, Listener, interfaces y adaptadores, ActionListener,
WindowAdapter,…




Escuchador_WindowListener.java
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Escuchador_WindowListener extends WindowAdapter {

         public void windowClosing(WindowEvent evento){
                System.exit(0);
         }
}


Calculadora.java

import   java.awt.BorderLayout;
import   java.awt.Color;
import   java.awt.Frame;
import   java.awt.TextField;
import   java.awt.Panel;
import   java.awt.GridLayout;
import   java.awt.Button;
import   java.awt.event.ActionEvent;
import   java.awt.event.ActionListener;
import   java.awt.event.KeyEvent;
import   java.awt.event.KeyListener;

public class Calculadora extends Frame implements ActionListener,KeyListener{

         private static final long serialVersionUID = 1L;

         private   TextField pantalla = null;
         private   Button tecla = null;
         private   int operando1 = 0;
         private   int operando2 = 0;
         private   String operacion = null;
         private   boolean newDigitBlock = true;




                                                                              bitCoach::Juan Bautista Cascallar Lorenzo
//Constructor
public Calculadora(){

       this.setTitle("Calculadora");
       this.setSize(200, 200);
       this.setLayout(new BorderLayout());
       this.addWindowListener(new Escuchador_WindowListener());

       //--- Display ---
       pantalla = new TextField();
       pantalla.setText("0");
       pantalla.addKeyListener(this);
       pantalla.setBackground(Color.CYAN);
       this.add(pantalla,BorderLayout.NORTH);

       //--- Teclas ---
       Panel panel01 = new Panel();
       panel01.setLayout(new GridLayout(5,3));
       tecla = new Button("0"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("1"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("+"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("2"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("3"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("-"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("4"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("5"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("="); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("6"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("7"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("C"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("8"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button("9"); tecla.addActionListener(this); panel01.add(tecla);
       tecla = new Button(); tecla.setEnabled(false); panel01.add(tecla);
       this.add(panel01,BorderLayout.CENTER);
}

//--- Método de la interfaz ActionListener ---
@Override
public void actionPerformed(ActionEvent e) {
       // TODO Auto-generated method stub
       String teclaPulsada = ((Button)e.getSource()).getLabel();

       if(teclaPulsada.equals("C")){
               pantalla.setText("0");
               operando1 = 0;
               operando2 = 0;
               newDigitBlock = true;
       }else if(teclaPulsada.equals("=")){
               operando2 = Integer.parseInt(pantalla.getText());
               if(operacion != null){
                      if(operacion.equals("+")){
                              pantalla.setText(new Integer(operando1 + operando2).toString());
                      }else if (operacion.equals("-")){
                              pantalla.setText(new Integer(operando1 - operando2).toString());
                      }
               }
               newDigitBlock = true;
               operacion = null;
       }else if(teclaPulsada.equals("+") || teclaPulsada.equals("-")){
               operacion = teclaPulsada;
               operando1 = Integer.parseInt(pantalla.getText());
               newDigitBlock = true;
       }else{
               if(newDigitBlock == true){
                      pantalla.setText(teclaPulsada);
                      newDigitBlock = false;
               }else{
                      pantalla.setText(pantalla.getText() + teclaPulsada);
                      //--- Quitar 0 al principio ---
                      if((pantalla.getText().length() > 1) && (pantalla.getText().charAt(0) == '0')){
                              pantalla.setText(pantalla.getText().substring(1));
                      }
               }
       }
}//Fin function

                                                                   bitCoach::Juan Bautista Cascallar Lorenzo
//--- Métodos de la interfaz KeyListener ---
       @Override
       public void keyTyped(KeyEvent e) {
              // TODO Auto-generated method stub

       }

       @Override
       public void keyPressed(KeyEvent e) {
              // TODO Auto-generated method stub

       }

       @Override
       public void keyReleased(KeyEvent e) {
              // TODO Auto-generated method stub

       }

}

TestCalculadora.java

public class TestCalculadora {

       public static void main(String[] args) {
              // TODO Auto-generated method stub

              Calculadora c = new Calculadora();
              //c.pack();
              c.setVisible(true);
       }
}




                                                      bitCoach::Juan Bautista Cascallar Lorenzo

More Related Content

PPTX
Jdk,jre,jvm
PPT
Java Programming for Designers
PDF
Learn Java with Dr. Rifat Shahriyar
PDF
Introduction to java (revised)
PPTX
PPT
Java awt
PDF
Transacciones y sql procedural EN MySQL
PPT
Regular expressions and languages pdf
Jdk,jre,jvm
Java Programming for Designers
Learn Java with Dr. Rifat Shahriyar
Introduction to java (revised)
Java awt
Transacciones y sql procedural EN MySQL
Regular expressions and languages pdf

What's hot (20)

PPTX
Lex Tool
DOCX
Trabajo sobre archivos en java.. programacion no numerica ii
PPTX
Scientific Calculator.pptx
PPTX
Introduction to Basic Java Versions and their features
PPTX
input buffering in lexical analysis in CD
PPT
Algorithms and flowcharts ppt (seminar presentation)..
PPTX
Unidad 3 topicos avanzados de programacion
PDF
Ejercicios resueltos de java
PPTX
Tipos de datos, identificadores, variables y constantes
PPTX
Definición de Subprograma
PPTX
arboles avl con codigo en java
PDF
20 ejercicios propuestos
PPTX
Lex programming
PDF
Guía básica para programar en PSeint
PPTX
Introduction to java
PDF
Java - Exception Handling Concepts
PPTX
Constructor in java
PPTX
1-introduction-to-dart-programming.pptx
PDF
20 problemas
PPTX
C# Events
Lex Tool
Trabajo sobre archivos en java.. programacion no numerica ii
Scientific Calculator.pptx
Introduction to Basic Java Versions and their features
input buffering in lexical analysis in CD
Algorithms and flowcharts ppt (seminar presentation)..
Unidad 3 topicos avanzados de programacion
Ejercicios resueltos de java
Tipos de datos, identificadores, variables y constantes
Definición de Subprograma
arboles avl con codigo en java
20 ejercicios propuestos
Lex programming
Guía básica para programar en PSeint
Introduction to java
Java - Exception Handling Concepts
Constructor in java
1-introduction-to-dart-programming.pptx
20 problemas
C# Events
Ad

Viewers also liked (20)

PDF
Java Thread Cronometro
PDF
Sincronizar Threads
PDF
Java::Acceso a Bases de Datos
PDF
Acceso a BBDD mediante un servlet
PDF
Java AWT Tres en Raya
PDF
Servlets que manejan datos de formularios HTML
PDF
jQuery Mobile :: Cuadros de diálogo
PDF
jQuery Mobile :: Enlaces a páginas internas.
PDF
Word VBA
PDF
Programa Java que gestiona los productos que comercializan varios viveros
PDF
Acciones JSP
PDF
Explicación del código del Servlet HolaMundo
PDF
Jsp directiva page
PDF
Find File Servlet DB
PDF
Proyecto JSP
PDF
Elementos de script en JSP
PDF
Servlet Hola Mundo con Eclipse y Tomcat
PDF
Configurar entorno Android
PDF
MIT App Inventor2 Pintar en Imagen
PDF
App Android MiniBanco
Java Thread Cronometro
Sincronizar Threads
Java::Acceso a Bases de Datos
Acceso a BBDD mediante un servlet
Java AWT Tres en Raya
Servlets que manejan datos de formularios HTML
jQuery Mobile :: Cuadros de diálogo
jQuery Mobile :: Enlaces a páginas internas.
Word VBA
Programa Java que gestiona los productos que comercializan varios viveros
Acciones JSP
Explicación del código del Servlet HolaMundo
Jsp directiva page
Find File Servlet DB
Proyecto JSP
Elementos de script en JSP
Servlet Hola Mundo con Eclipse y Tomcat
Configurar entorno Android
MIT App Inventor2 Pintar en Imagen
App Android MiniBanco
Ad

More from jubacalo (12)

PDF
Cronómetro con MIT App Inventor 2
PDF
Crear Base de Datos en Oracle
PDF
Web de noticias en Ajax
PDF
Escenarios
PDF
Matrices02
PDF
Gráficos
PDF
Tabla Dinámica
PDF
Tabla de Datos
PDF
Textura de agua
PDF
Funciones lógicas y condicionales
PDF
Solver
PDF
Java Thread Cronometro
Cronómetro con MIT App Inventor 2
Crear Base de Datos en Oracle
Web de noticias en Ajax
Escenarios
Matrices02
Gráficos
Tabla Dinámica
Tabla de Datos
Textura de agua
Funciones lógicas y condicionales
Solver
Java Thread Cronometro

Recently uploaded (7)

PDF
15 AUG 2025 PS 15 AUG 2025 PS 15 AUG 2025 PS
PDF
ಶ್ರೀ ಕ್ಷೇತ್ರ ಚಂಪಕಧಾಮ ಸ್ವಾಮಿ ದೇವಾಲಯSri Kshetra Champakadham Swamy Temple
PDF
فورمولر عمومی مضمون فزیک برای همه انجنیران
PPTX
science grade 7 quiz_Scientific Method.pptx
PPTX
Coklat Beige Ilustrasi 3 Dimensi Tugas Kelompok Presentasi.pptx
PDF
Materi seni rupa untuk sekolah dasar materi tentang seni rupa
PPTX
Tahfidz Qur’an TIMING tampa musik bagian 2.pptx
15 AUG 2025 PS 15 AUG 2025 PS 15 AUG 2025 PS
ಶ್ರೀ ಕ್ಷೇತ್ರ ಚಂಪಕಧಾಮ ಸ್ವಾಮಿ ದೇವಾಲಯSri Kshetra Champakadham Swamy Temple
فورمولر عمومی مضمون فزیک برای همه انجنیران
science grade 7 quiz_Scientific Method.pptx
Coklat Beige Ilustrasi 3 Dimensi Tugas Kelompok Presentasi.pptx
Materi seni rupa untuk sekolah dasar materi tentang seni rupa
Tahfidz Qur’an TIMING tampa musik bagian 2.pptx

Java AWT Calculadora

  • 1. En esta práctica vamos a crear una sencilla calculadora utilizando el framework AWT (Abstract Window Toolkit) de Java. Etiquetas: Frame, Panel, paquete AWT, Gestión de eventos, Notificador, Listener, interfaces y adaptadores, ActionListener, WindowAdapter,… Escuchador_WindowListener.java import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Escuchador_WindowListener extends WindowAdapter { public void windowClosing(WindowEvent evento){ System.exit(0); } } Calculadora.java import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.TextField; import java.awt.Panel; import java.awt.GridLayout; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class Calculadora extends Frame implements ActionListener,KeyListener{ private static final long serialVersionUID = 1L; private TextField pantalla = null; private Button tecla = null; private int operando1 = 0; private int operando2 = 0; private String operacion = null; private boolean newDigitBlock = true; bitCoach::Juan Bautista Cascallar Lorenzo
  • 2. //Constructor public Calculadora(){ this.setTitle("Calculadora"); this.setSize(200, 200); this.setLayout(new BorderLayout()); this.addWindowListener(new Escuchador_WindowListener()); //--- Display --- pantalla = new TextField(); pantalla.setText("0"); pantalla.addKeyListener(this); pantalla.setBackground(Color.CYAN); this.add(pantalla,BorderLayout.NORTH); //--- Teclas --- Panel panel01 = new Panel(); panel01.setLayout(new GridLayout(5,3)); tecla = new Button("0"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("1"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("+"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("2"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("3"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("-"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("4"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("5"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("="); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("6"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("7"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("C"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("8"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button("9"); tecla.addActionListener(this); panel01.add(tecla); tecla = new Button(); tecla.setEnabled(false); panel01.add(tecla); this.add(panel01,BorderLayout.CENTER); } //--- Método de la interfaz ActionListener --- @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String teclaPulsada = ((Button)e.getSource()).getLabel(); if(teclaPulsada.equals("C")){ pantalla.setText("0"); operando1 = 0; operando2 = 0; newDigitBlock = true; }else if(teclaPulsada.equals("=")){ operando2 = Integer.parseInt(pantalla.getText()); if(operacion != null){ if(operacion.equals("+")){ pantalla.setText(new Integer(operando1 + operando2).toString()); }else if (operacion.equals("-")){ pantalla.setText(new Integer(operando1 - operando2).toString()); } } newDigitBlock = true; operacion = null; }else if(teclaPulsada.equals("+") || teclaPulsada.equals("-")){ operacion = teclaPulsada; operando1 = Integer.parseInt(pantalla.getText()); newDigitBlock = true; }else{ if(newDigitBlock == true){ pantalla.setText(teclaPulsada); newDigitBlock = false; }else{ pantalla.setText(pantalla.getText() + teclaPulsada); //--- Quitar 0 al principio --- if((pantalla.getText().length() > 1) && (pantalla.getText().charAt(0) == '0')){ pantalla.setText(pantalla.getText().substring(1)); } } } }//Fin function bitCoach::Juan Bautista Cascallar Lorenzo
  • 3. //--- Métodos de la interfaz KeyListener --- @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } } TestCalculadora.java public class TestCalculadora { public static void main(String[] args) { // TODO Auto-generated method stub Calculadora c = new Calculadora(); //c.pack(); c.setVisible(true); } } bitCoach::Juan Bautista Cascallar Lorenzo