Download - Introducción POO
![Page 1: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/1.jpg)
José Antonio García Mejía 1
Introducción a la POO
![Page 2: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/2.jpg)
José Antonio García Mejía 2
Objetivo
Conocer los principios de la POO y aplicarlos en el lenguaje Java
![Page 3: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/3.jpg)
José Antonio García Mejía 3
Características
Abstracción Encapsulamiento Herencia PolimorfismoExplicar con ejemplos prácticos
![Page 4: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/4.jpg)
José Antonio García Mejía 4
Abstracción
“ELIMINAR LO IRRELEVANTE Y AMPLIFICAR LO
ESENCIAL”
![Page 5: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/5.jpg)
José Antonio García Mejía 5
Abstracción
Granularidad A los elementos en el dominio del
problema y su representación en el dominio de la solución se le llama OBJETO.
Abstracción de datos
![Page 6: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/6.jpg)
José Antonio García Mejía 6
Tipo de dato abstracto
Un tipo abstracto de datos define una especie de caja negra
ModeloAbstracción
![Page 7: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/7.jpg)
José Antonio García Mejía 7
Encapsulamiento Encapsular es agrupar en una misma entidad las estructuras de
datos y las funciones, ocultando la implementación bajo una interface.
Implementación es la manera cómo se llevan a cabo las operaciones, es decir que tipo de datos se utilizan, cuanta memoria utilizan, etc.
Si todos los datos miembro de una clase estuvieran disponibles para cualquiera, entonces el cliente podrá hacer lo que quiera con la clase y no habría manera de forzar un comportamiento en especial. De ahí, la necesidad de mantener claramente separada y protegida la interface y la implementación.
![Page 8: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/8.jpg)
José Antonio García Mejía 8
Herencia Definición (Herencia). Herencia es
el mecanismo que permite que un clase A herede propiedades de una clase B. Decimos "A hereda de B". Objetos de la clase A tienen así acceso a los atributos y métodos de la clase B sin necesidad de redefinirlos.
Definición (Superclase/Subclase)Si la clase A hereda de la clase B, entonces B es la superclase de A. A es subclase de B.
A
B
![Page 9: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/9.jpg)
José Antonio García Mejía 9
Polimorfismo– “poly” muchos, varios– “morph” forma o apariencia.
En la programación orientada a objetos, “morph” forma se refiere a la interface o a las propiedades de los objetos mientras que “poly” que las la interface o los atributos de los objetos son diferentes.
Las interfaces son fundamentales en los sistemas orientados a objetos ya que es la manera de conocerlos.
Se dice que dos o mas objetos son polimórficos si tienen interfaces idénticas pero comportamiento diferente; desde el punto de vista del cliente esos objetos son indistinguibles.
El polimorfismo se logra cuando una clase hereda la interfaz de otra clase ya sea total o parcial o bien, con tipo o sin tipo.
![Page 10: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/10.jpg)
José Antonio García Mejía 10
Objeto y claseEn la Programación orientada a objetos cualquier cosa es un
objeto, mantienen un estado que indica sus transiciones y tienen métodos que sirven para que expresar un comportamiento deseado.
Se puede ver a un objeto como una caja negra la cual contiene código (secuencia de instrucciones) y datos (información sobre la cual actúan las instrucciones). Tradicionalmente el código y los datos son entidades separadas, por ejemplo en el lenguaje C, las unidades de código son las funciones mientras que las unidades de información son las estructuras.
Un programa es un conjunto de objetos comunicándose entre ellos mediante mensajes.
![Page 11: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/11.jpg)
José Antonio García Mejía 11
Objeto y claseLa clase implementa al tipo. Un objeto se define por medio de su clase de ahí que un objeto
sea una instancia individual de una clase. Al proceso de crear un objeto se le llama instanciación.
Una clase es la combinación de estructuras, funciones e interfaces.
La interfaz de una clase es todo lo visible para aquellas funciones que no forman parte de la clase. Las funciones clientese comunican con la clase mediante la invocación de su interfaz.
Los objetos están protegidos por una interfaz: el contrato entre el objeto y el cliente.
Todos los objetos de un mismo tipo pueden recibir los mismos mensajes.
![Page 12: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/12.jpg)
José Antonio García Mejía 12
Objeto y clase
objeto
código
código
método
método
datos
interfaz
implementación
Nombre de la Clase
Atributos
Métodos
![Page 13: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/13.jpg)
José Antonio García Mejía 13
Objeto y clase Las solicitudes que se puden hacer a
un objeto están definidas por su interface. El tipo del objeto determina la interface de éste.
Light lt;lt.on();
![Page 14: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/14.jpg)
José Antonio García Mejía 14
Objeto y clase En el ámbito de la programación, existen creadores de clases
(aquellos que crean nuevos tipos de datos) y programadores clientes (aquellos que usan las clases creadas por los primeros).
La meta del programador cliente es coleccionar una completa caja de herramientas de clases que le permita el rápido desarrollo de aplicaciones.
La meta del creador de las clases es exponer únicamente lo que necesita el programador cliente y manterner lo demás oculto.
![Page 15: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/15.jpg)
José Antonio García Mejía 15
Objeto y clase
Especificaciones de estado: Las clases describen la manera de almacenar la información del estado dentro de sus instancias. Los tipos de variables dentro de una clase se clasifican en dos categorías:
Variables de instancia: Son variables que aparecen cada vez que se instancia un objeto.
Variables de Clase: Son variables que contienen datos que sólo son relevantes a la clase misma y no a cualquier instancia de clase. Una variable de clase la comparten todos los objetos de la clase.
![Page 16: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/16.jpg)
José Antonio García Mejía 16
Objeto y clase
Especificación del comportamiento: El algoritmo que define el comportamiento de un objeto se especifica en la clase del objeto y al igual que las variables se catalogan en dos grupos:
Métodos de Instancia: Son funciones que manipulan al estado de un objeto en particular.
Métodos de Clase: Son funciones que son relevantes a una clase, pero no operan en alguna instancia en particular de la clase. Se pueden usar para crear nuevas instancias de clase.
![Page 17: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/17.jpg)
José Antonio García Mejía 17
Clases y objetos
![Page 18: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/18.jpg)
José Antonio García Mejía 18
Introducción a la programación en Java
![Page 19: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/19.jpg)
José Antonio García Mejía 19
¿Qué es Java?
Es un lenguaje de OOP, desarrollado por Sun Microsystems, diseñado para ser pequeño, sencillo y portátil a través de plataformas y sistemas operativos, tanto a nivel de código fuente como en binario
![Page 20: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/20.jpg)
José Antonio García Mejía 20
Historia de Java (1)• Fue desarrollado por Sun Microsystems en 1991, se llamóOak.
• Creación de software para dispositivos electrónicos (TV, VCR, tostadores).
• En 1994 se escribe WebRunner (HotJava).
![Page 21: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/21.jpg)
José Antonio García Mejía 21
Historia de Java (2)
• En 1994 se reescribe el compilador de Java en Java a partir de su original en C.
• Sun introduce Java en 1995 en la Sun World 95 convention.
![Page 22: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/22.jpg)
José Antonio García Mejía 22
Características de Java
• Simple.
• Orientado a objetos.
• Distribuido
• Robusto.
• Arquitectura neutral.
![Page 23: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/23.jpg)
José Antonio García Mejía 23
Java es un lenguaje Multiplataforma
![Page 24: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/24.jpg)
José Antonio García Mejía 24
Compilación de un programa en Java
![Page 25: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/25.jpg)
José Antonio García Mejía 25
Programas en Java
![Page 26: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/26.jpg)
José Antonio García Mejía 26
Características de Java
• Seguro.
• Portable
• Interpretado.
• Multihilos.
• Dinámico.
![Page 27: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/27.jpg)
José Antonio García Mejía 27
Java para aplicaciones (1)
¿Es Java en realidad es una buena tecnología para desarrollar aplicaciones corporativas?
A continuación se muestran algunas necesidades importantes del desarrollo de aplicaciones
![Page 28: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/28.jpg)
José Antonio García Mejía 28
Java para aplicaciones (2)
• Desarrollo rápido de aplicaciones
• Aplicaciones efectivas y eficientes
• Portabilidad para programador y programa
![Page 29: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/29.jpg)
José Antonio García Mejía 29
Java para aplicaciones (3)
• Costos de desarrollo
• Mantenimiento y soporte
• Aprendizaje
![Page 30: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/30.jpg)
José Antonio García Mejía 30
Instalación de Java
El programa de instalación se encuentra en el CD
Seguir los siguientes pasos– Copiar el archivo a su máquina– Ejecutar el archivo jdk1_2_2-000-win.exe– Modificar agregar c:\jdk1.2.2\bin en la
variable PATH, del archivo autoexec.bat
![Page 31: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/31.jpg)
José Antonio García Mejía 31
Construcción y compilación de programas en Java
![Page 32: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/32.jpg)
José Antonio García Mejía 32
Tipos de Programas en Java
Aplicaciones.- Los programas se ejecutan en consolas
Applet.- Los programas se ejecutan en un browser o navegador de la Web
![Page 33: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/33.jpg)
José Antonio García Mejía 33
Primer programa en Java
1: class HelloWorld 2: {3: public static void main (String args[ ]) 4: {5: System.out.println("Hello World!");6: }7: }
![Page 34: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/34.jpg)
José Antonio García Mejía 34
Compilación en Java
javac HelloWorld.java
![Page 35: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/35.jpg)
José Antonio García Mejía 35
Ejecución del programa
java HelloWorld
![Page 36: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/36.jpg)
José Antonio García Mejía 36
Primer Applet en Java
1: import java.awt.Graphics;2: public class HelloWorldApplet
extends java.applet.Applet 3: {4: public void paint(Graphics g) 5: {6: g.drawString("Hello world!", 5,
25);7: }8: }
![Page 37: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/37.jpg)
José Antonio García Mejía 37
Página HTML para el Applet
1: <HTML>2: <HEAD>3: <TITLE>Hola a Todos!</TITLE>4: </HEAD>5: <BODY>6: <P>Mi primer Applet Dice:7: <APPLET Code=“HolaMundoApplet.class“8: width=150 height=25>9: </APPLET>10: </BODY>11:</HTML>
![Page 38: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/38.jpg)
José Antonio García Mejía 38
Ejecución del Applet
• Compile.
javac HolaMundoApplet.java
• Ejecutar el Applet.appletviewer HolaMundoApplet.html
![Page 39: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/39.jpg)
José Antonio García Mejía 39
Tipos de clases en Java
•Abstract
•final
•public
•synchronizable
![Page 40: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/40.jpg)
José Antonio García Mejía 40
Métodos y atributos
Cada clase que escribe en Java estáformada por dos componentes:
atributos y comportamiento
![Page 41: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/41.jpg)
José Antonio García Mejía 41
Atributos
Son las características individuales, que diferencian a un objeto de otro, y determinan la apariencia, estado u
otras cualidades de ese objeto.
![Page 42: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/42.jpg)
José Antonio García Mejía 42
Atributos
Los atributos se definen con variables. Cada instancia de una
clase puede tener diferentes valores para sus variables, por lo que cada
variable se le llama variable de instancia
![Page 43: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/43.jpg)
José Antonio García Mejía 43
Métodos
Se establece a través de un conjunto de funciones, llamados métodos,
definidas dentro de las clases.
![Page 44: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/44.jpg)
José Antonio García Mejía 44
Creando una clase
class Motorcycle {
}
![Page 45: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/45.jpg)
José Antonio García Mejía 45
Agregando atributos
String make;String color;boolean engineState = false;
![Page 46: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/46.jpg)
José Antonio García Mejía 46
Agregando métodosvoid startEngine( )
{if (engineState == true)
System.out.println("The engine is already on.");
else {engineState = true;
System.out.println("The engine is now on.");
}}
![Page 47: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/47.jpg)
José Antonio García Mejía 47
Agregando métodos
void showAtts() {System.out.println("This motorcycle is a "
+ color + " " + make);if (engineState == true)
System.out.println("The engine is on.");else System.out.println("The engine is off.");
}
![Page 48: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/48.jpg)
José Antonio García Mejía 48
Agregando el método main()1: public static void main (String args[])2: {3: Motorcycle m = new Motorcycle();4: m.make = "Yamaha RZ350";5: m.color = "yellow";6: System.out.println("Calling showAtts...");7: m.showAtts();8: System.out.println("--------");9: System.out.println("Starting engine...");10: m.startEngine();11: System.out.println("--------");12: System.out.println("Calling showAtts...");13: m.showAtts();14: System.out.println("--------");15: System.out.println("Starting engine...");16: m.startEngine();17: }
![Page 49: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/49.jpg)
José Antonio García Mejía 49
Salida del programa
Calling showAtts...This motorcycle is a yellow Yamaha RZ350The engine is off.--------Starting engine...The engine is now on.--------Calling showAtts...This motorcycle is a yellow Yamaha RZ350The engine is on.--------Starting engine...The engine is already on.
![Page 50: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/50.jpg)
José Antonio García Mejía 50
Alcance de objetos y reciclado de memoria
En Java, la recolección y liberación de memoria es responsabilidad de un threadllamado automatic garbage collector (recolector automático de basura).
![Page 51: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/51.jpg)
José Antonio García Mejía 51
Herencia (1)
Permite la creación de nuevas clases a partir de clases existentes, definiendo
solamente las diferencias existentes entre ambas.
![Page 52: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/52.jpg)
José Antonio García Mejía 52
Herencia (2)
Clase A
Clase B
Clase C Clase D Clase E
![Page 53: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/53.jpg)
José Antonio García Mejía 53
Subclasificación
Crear una nueva clase que heredará atributos y métodos de alguna otra
clase en la jerarquía.
![Page 54: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/54.jpg)
José Antonio García Mejía 54
Una jerarquía de clases
Object
Vehiculo
VehiculoPersonal VehiculoGrupo
![Page 55: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/55.jpg)
José Antonio García Mejía 55
Una jerarquía de clasesObject
Vehiculo
Vehiculo_Dos_Llantas Vehiculo_Cuatro_Llantas
Moto Automovil Camion
![Page 56: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/56.jpg)
José Antonio García Mejía 56
¿Cómo funciona la herencia?
![Page 57: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/57.jpg)
José Antonio García Mejía 57
¿Cómo sobreponer métodos?
![Page 58: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/58.jpg)
José Antonio García Mejía 58
Java solo contempla la herencia simple,
pero se puede simular la herencia múltiple
![Page 59: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/59.jpg)
José Antonio García Mejía 59
Modificadores de acceso
• public
• protected
• private
• friendly
![Page 60: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/60.jpg)
José Antonio García Mejía 60
Creando una subclase1:import java.awt.Graphics;2:import java.awt.Font;3:import java.awt.Color;4:5:public class HolaOApplet extends java.applet.Applet6: {7:8: Font f = new Font("TimesRoman",Font.BOLD,36);9:10: public void paint(Graphics g) 11: {12: g.setFont(f);13: g.setColor(Color.red);14: g.drawString(“Hola Otra vez!", 5, 40);15: }16: }
![Page 61: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/61.jpg)
José Antonio García Mejía 61
Página HTML para el Applet<HTML>
<HEAD><TITLE>Otro Applet</TITLE>
</HEAD><BODY><P>Mi Segundo Applet dice:<BR><APPLET Code="HolaOApplet.class" Width=200
Height=50></APPLET>
</BODY></HTML>
![Page 62: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/62.jpg)
José Antonio García Mejía 62
Salida del Applet
![Page 63: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/63.jpg)
José Antonio García Mejía 63
Variables y métodos estáticos
Sirven para crear una clase en la que el valor de una variable de instancia sea el mismo para todos los objetos instanciados a partir de esa clase.
![Page 64: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/64.jpg)
José Antonio García Mejía 64
Tipos de variables
•Variables de instancia.
•Variables de clase.
•Variables locales.
![Page 65: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/65.jpg)
José Antonio García Mejía 65
Declaración de variables
int myAge;String myName;boolean isTired;int x, y, z;String firstName, LastName;int myAge, mySize, numShoes = 28;String myName = "Laura";boolean isTired = true;int a = 4, b = 5, c = 6;
![Page 66: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/66.jpg)
José Antonio García Mejía 66
Tipos de datos
•int
•float
•String
•char
•boolean
•byte
•short
•long
![Page 67: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/67.jpg)
José Antonio García Mejía 67
Tipos de constantes
•Número
•String
•char
•boolean
•long
![Page 68: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/68.jpg)
José Antonio García Mejía 68
Operadores
+,-,*,/
+=, -=, *=, /=
++,--
==, !=, <, >, <=, >=
![Page 69: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/69.jpg)
José Antonio García Mejía 69
Precedencia de operadores (1)
. [ ] ( )
++ -- ! instanceof
new (tipo) expresión
* / %
+ -
< > <= >=
![Page 70: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/70.jpg)
José Antonio García Mejía 70
Precedencia de operadores (2)
== !=
&&
| |
? :
= += -= *= /= %=
![Page 71: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/71.jpg)
José Antonio García Mejía 71
¿Cómo crear nuevos objetos?
String str=new String();
Random r = new Random();
Motorcycle m2= new Motorcycle()
![Page 72: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/72.jpg)
José Antonio García Mejía 72
Lo que hace new
•Crea una nueva instancia de la clase dada.
•Se llama al método constructor.
![Page 73: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/73.jpg)
José Antonio García Mejía 73
Método constructor
Es un método especial para crear e inicializar nuevas
instancias de clase. Tiene el mismo nombre de la clase y no posee un tipo de retorno.
![Page 74: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/74.jpg)
José Antonio García Mejía 74
Acceso a las variables de instancia y de clase
Con la notación de punto, un nombre de variable de
instancia o de clase tiene dos partes:
objeto.variable
![Page 75: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/75.jpg)
José Antonio García Mejía 75
Variables de instancia
Point thePoint = new Point(10,10);
thePoint.x = 5;
System.out.println(“Y es :”+thePoint.y);
![Page 76: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/76.jpg)
José Antonio García Mejía 76
Variables de clase
class FamilyMember {
static String surname = “Johnson”;
String name;
int age;
}
![Page 77: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/77.jpg)
José Antonio García Mejía 77
Métodos de instancia
myObject.methodOne(arg1,arg2,arg3);
myObject.methodNoArgs();
myObject.getClass().getName();
myObject.var.methodTwho(arg1,arg2);
![Page 78: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/78.jpg)
José Antonio García Mejía 78
Métodos de clase
Clase.myMetod();
String.valueOf(5);
![Page 79: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/79.jpg)
José Antonio García Mejía 79
Cast en tipos primitivos
(typename) value
(int) x/y;
(String) arg;
![Page 80: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/80.jpg)
José Antonio García Mejía 80
Cast de objetos
(classname) object
GreenApple a;
Apple a2;
a = new GreenApple();
a2 = (Apple) a;
![Page 81: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/81.jpg)
José Antonio García Mejía 81
Comparación de objetos
El único tipo de comparación que se puede llevar a cabo entre los objetos
es con los operadores:
== (igual)
!= (diferente)
Object.equals(Object Object)
![Page 82: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/82.jpg)
José Antonio García Mejía 82
Ejemplo de igualdad en Strings
1: class EqualsTest {2: public static void main(String args[]) {3: String str1, str2;4: str1 = "she sells sea shells by the sea
shore.";5: str2 = str1;6: 7: System.out.println("String1: " + str1);8: System.out.println("String2: " + str2);9: System.out.println("Same object? " + (str1 ==
str2));
![Page 83: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/83.jpg)
José Antonio García Mejía 83
Prueba de igualdad
10: 11: str2 = new String(str1);12: 13: System.out.println("String1: " + str1);14: System.out.println("String2: " + str2);15: System.out.println("Same object? " + (str1
== str2));16: System.out.println("Same value? " +
str1.equals(str2));17: }18: }
![Page 84: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/84.jpg)
José Antonio García Mejía 84
Determinación de la clases de un objeto
String name = obj.getClass().getName();
"foo" instanceof String // truePoint pt = new Point(10, 10);pt instanceof String // false
![Page 85: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/85.jpg)
José Antonio García Mejía 85
Paquetes de clases en Java
•java.lang•java.util•java.net•java.awt•java.applet
![Page 86: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/86.jpg)
José Antonio García Mejía 86
Arreglos
Son una forma de almacenar una lista de elementos. En Java
son verdaderos objetos que pueden pasarse y tratarse de la
misma manera que otros objetos.
![Page 87: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/87.jpg)
José Antonio García Mejía 87
Pasos para crear arreglos
• Declare una variable para guardar el arreglo.
• Cree un nuevo objeto de arreglo y asígnelo a la variable de arreglo.
• Guarde lo que desee en el arreglo.
![Page 88: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/88.jpg)
José Antonio García Mejía 88
Declaración de arreglos
String[ ] difficultWords;
Point[ ] hits;
int[ ] temps;
![Page 89: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/89.jpg)
José Antonio García Mejía 89
Creando arreglos de objetos
•String[] names = new String[10];
•int[ ] temps = new int[99];
•String[ ] chiles = { "jalapeno", "anaheim", "serrano", "habanero", "thai" };
![Page 90: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/90.jpg)
José Antonio García Mejía 90
Acceso a los elementos de un arreglo
myArray[subscript]
![Page 91: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/91.jpg)
José Antonio García Mejía 91
Arreglos multidimensionales
int coords[ ][ ] = new int[12][12];coords[0][0] = 1;coords[0][1] = 2;
![Page 92: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/92.jpg)
José Antonio García Mejía 92
Sentencia ifif (x < y)
System.out.println("x is smaller thany");if (x < y)
System.out.println("x is smaller thany");
else System.out.println("y is bigger");
![Page 93: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/93.jpg)
José Antonio García Mejía 93
Condicionales ifif (engineState == true )
System.out.println("Engine is already on.");
else {System.out.println("Now starting
Engine.");if (gasLevel >= 1)
engineState = true;else System.out.println("Low on gas! Can't
start engine.");
![Page 94: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/94.jpg)
José Antonio García Mejía 94
Sentencia switchswitch (test) {
case valueOne: resultOne;break;
case valueTwo: resultTwo;break;
case valueThree: resultThree;break;
...default: defaultresult;
}
![Page 95: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/95.jpg)
José Antonio García Mejía 95
Condicional switch
switch (x) {case 2:case 4:case 6:case 8:
System.out.println("x is an even number.");break;
default: System.out.println("x is an odd number.");}
![Page 96: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/96.jpg)
José Antonio García Mejía 96
Condicional switch1: class NumberReader {2:3: String convertNum(int val) {4: switch (val) {5: case 0: return "zero ";6: case 1: return "one ";7: case 2: return "two ";8: case 3: return "three ";9: case 4: return "four ";10: case 5: return "five ";11: case 6: return "six ";12: case 7: return "seven ";
![Page 97: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/97.jpg)
José Antonio García Mejía 97
Condicional switch
13: case 8: return "eight ";14: case 9: return "nine ";15: default: return " ";16: }17: }18: 19: public static void main (String args[]) {20: NumberReader n = new NumberReader();21: String num = n.convertNum(4) +
n.convertNum(1) + n.convertNum(5);22: System.out.println("415 converts to " +
num);23: }24:}
![Page 98: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/98.jpg)
José Antonio García Mejía 98
Ciclos for
for (initialization; test; increment) {statements;
}
![Page 99: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/99.jpg)
José Antonio García Mejía 99
Ciclos for1: class NamesLoop {2:3: String[] firstNames = { "Dennis",
"Grace", "Bjarne", "James" };4: String[] lastNames = new
String[firstNames.length];5: 6: void printNames() {7: for (int i = 0; i < firstNames.length; i++) 8: System.out.println(firstNames[i] + " "
+ lastNames[i]); 9: }
![Page 100: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/100.jpg)
José Antonio García Mejía 100
Ciclos for
10: 11: public static void main (String args[]) {12: ArrayTest a = new ArrayTest();13: a.printNames();14: System.out.println("----------");15: a.lastNames[0] = "Ritchie";16: a.lastNames[1] = "Hopper";17: a.lastNames[2] = "Stroustrup";18: a.lastNames[3] = "Gosling";19: 20: a.printNames(); 21:}22:}
![Page 101: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/101.jpg)
José Antonio García Mejía 101
Ciclos while
while (condition) {bodyOfLoop;
}
![Page 102: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/102.jpg)
José Antonio García Mejía 102
Ciclos while1: class CopyArrayWhile {2: public static void main (String args[]) {3: int[] array1 = { 5, 7, 3, 6, 0, 3, 2, 1 };4: float[] array2 = new float[array1.length];5: 6: System.out.print("array1: [ ");7: for (int i = 0; i < array1.length; i++) {8: System.out.print(array1[i] + " ");9: }10: System.out.println("]");
![Page 103: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/103.jpg)
José Antonio García Mejía 103
Ciclos while
11: 12: System.out.print("array2: [ ");13: int count = 0;14: while ( count < array1.length &&
array1[count] != 0) { 15: array2[count] = (float) array1[count];16: System.out.print(array2[count++] + "
");17: }18: System.out.println("]");19: }20:}
![Page 104: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/104.jpg)
José Antonio García Mejía 104
Ciclos do ... while
do {bodyOfLoop;
} while (condition);
![Page 105: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/105.jpg)
José Antonio García Mejía 105
Ciclos do ... while1: class DoTest {2: public static void main (String args[]) {3: int x = 1;4: 5: do {6: System.out.println("Looping, round " + x);7: x++;8: } while (x <= 10);9: }10: }
![Page 106: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/106.jpg)
José Antonio García Mejía 106
¿Cómo salir de los ciclos?
•break
•continue
![Page 107: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/107.jpg)
José Antonio García Mejía 107
Ejemplo del uso de break
int count = 0;while (count < array1.length) {
if (array1[count] == 0) {break;
}array2[count] = (float)
array1[count++];}
![Page 108: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/108.jpg)
José Antonio García Mejía 108
Ejemplo del uso de continue
int count1 = 0;int count2 = 0;while (count < array1.length) {
if (array1[count1] == 0) {continue;count1++
}array2[count2++] =
(float)array1[count1++];}
![Page 109: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/109.jpg)
José Antonio García Mejía 109
Definición de Clases
class MyClassName{
...}
![Page 110: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/110.jpg)
José Antonio García Mejía 110
Herencia
class myClassName extends mySuperClassName {...}
![Page 111: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/111.jpg)
José Antonio García Mejía 111
Constantes
final float pi = 3.141592;final boolean debug = false;final int maxsize = 40000;
![Page 112: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/112.jpg)
José Antonio García Mejía 112
Variables de clase
static int sum;static final int maxObjects = 10;
![Page 113: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/113.jpg)
José Antonio García Mejía 113
Métodos
returntype methodname(type1 arg1, type2 arg2, type3 arg3..) {
...}
![Page 114: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/114.jpg)
José Antonio García Mejía 114
La clase RangeClass
1: class RangeClass {2: int[] makeRange(int lower, int upper) {3: int arr[] = new int[ (upper - lower) + 1 ];4: 5: for (int i = 0; i < arr.length; i++) {6: arr[i] = lower++;7: }8: return arr;9: }10:
![Page 115: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/115.jpg)
José Antonio García Mejía 115
La clase RangeClass
11: public static void main(String arg[]) {12: int theArray[];13: RangeClass theRange = new RangeClass();14: 15: theArray = theRange.makeRange(1, 10);16: System.out.print("The array: [ ");17: for (int i = 0; i < theArray.length; i++) {18: System.out.print(theArray[i] + " ");19: }20: System.out.println("]");21: }22: 23: }
![Page 116: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/116.jpg)
José Antonio García Mejía 116
La palabra reservada thisHace referencia al objeto actual
t = this.x; this.myMethod(this); return this;
![Page 117: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/117.jpg)
José Antonio García Mejía 117
Pasando argumentos a los programas en Java
1: class EchoArgs {2: public static void main(String args[]) {3: for (int i = 0; i < args.length; i++) {4: System.out.println("Argument " + i + ": " + args[i]);5: }6: }7: }
![Page 118: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/118.jpg)
José Antonio García Mejía 118
Métodos constructores
Es una clase especial de método que determina como se inicializa un objeto cuando se
crea.
![Page 119: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/119.jpg)
José Antonio García Mejía 119
Constructores básicos
• Siempre tienen el mismo nombre de la clase.
• No tiene un tipo de retorno (return)
![Page 120: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/120.jpg)
José Antonio García Mejía 120
Sobrecargando constructores
1: import java.awt.Point;3: class MyRect2 {4: int x1 = 0;5: int y1 = 0;6: int x2 = 0;7: int y2 = 0;9: MyRect2(int x1, int y1, int x2, int y2) {10: this.x1 = x1;11: this.y1 = y1;12: this.x2 = x2;13: this.y2 = y2;14: }
![Page 121: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/121.jpg)
José Antonio García Mejía 121
Sobre carga de constructores
16: MyRect2(Point topLeft, Point bottomRight) {
17: x1 = topLeft.x;18: y1 = topLeft.y;19: x2 = bottomRight.x;20: y2 = bottomRight.y;21: }22: 23: MyRect2(Point topLeft, int w, int h) {24: x1 = topLeft.x;25: y1 = topLeft.y;26: x2 = (x1 + w);27: y2 = (y1 + h);28: }
![Page 122: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/122.jpg)
José Antonio García Mejía 122
Sobre carga de constructores
30: void printRect() {31: System.out.print("MyRect: <" + x1 +
", " + y1);32: System.out.println(", " + x2 + ", " +
y2 + ">");33: }
![Page 123: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/123.jpg)
José Antonio García Mejía 123
Sobre carga de constructores
35: public static void main(String args[]) {36: MyRect2 rect;37: 38: System.out.println("Calling MyRect2
with coordinates 25,25 50,50:");39: rect = new MyRect2(25, 25, 50,50);40: rect.printRect();41: System.out.println("----------");42: 43: System.out.println("Calling MyRect2
w/points (10,10), (20,20):");
![Page 124: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/124.jpg)
José Antonio García Mejía 124
Sobre carga de constructores
44: rect= new MyRect2(new Point(10,10), new Point(20,20));
45: rect.printRect();46: System.out.println("----------");47: 48: System.out.print("Calling MyRect2 w/1 point
(10,10)");49: System.out.println(" width (50) and height (50):");50: rect = new MyRect2(new Point(10,10), 50, 50);51: rect.printRect();52: System.out.println("----------");54: } }
![Page 125: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/125.jpg)
José Antonio García Mejía 125
Sobre carga de métodos
1: class PrintClass {2: int x = 0;3: int y = 1;4: 5: void printMe() {6: System.out.println("x is " + x + ", y is " + y);7: System.out.println("I am an instance of the
class " +8: this.getClass().getName());9: }
10: }
![Page 126: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/126.jpg)
José Antonio García Mejía 126
Sobre carga de métodos
1: class PrintSubClass extends PrintClass {2: int z = 3;3: 4: public static void main(String args[]) {5: PrintSubClass obj = new PrintSubClass();6: obj.printMe();7: }8: }
![Page 127: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/127.jpg)
José Antonio García Mejía 127
Sobre carga de métodos
1: class PrintSubClass2 extends PrintClass {2: int z = 3;3: 4: void printMe() {5: System.out.println("x is " + x + ", y is "
+ y +6: ", z is " + z);7: System.out.println("I am an instance of
the class " +8: this.getClass().getName());9: }
![Page 128: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/128.jpg)
José Antonio García Mejía 128
Sobre carga de métodos
11: public static void main(String args[]) {12: PrintSubClass2 obj = new
PrintSubClass2();13: obj.printMe();14: }15: }
![Page 129: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/129.jpg)
José Antonio García Mejía 129
Llamada del método original
// From PrintSubClass2
void printMe() {super.printMe();System.out.println("z is " + z);
}
![Page 130: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/130.jpg)
José Antonio García Mejía 130
“Sobreponiendo”Constructores
1: import java.awt.Point;2: class NamedPoint extends Point {3: String name;4:5: NamedPoint(int x, int y, String name) {6: super(x,y);7: this.name = name;8: }
![Page 131: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/131.jpg)
José Antonio García Mejía 131
“Sobreponiendo”Constructores
9: public static void main (String arg[]) {10: NamedPoint np = new NamedPoint(5,
5, "SmallPoint");11: System.out.println("x is " + np.x);12: System.out.println("y is " + np.y);13: System.out.println("Name is " +
np.name);14: }15:}
![Page 132: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/132.jpg)
José Antonio García Mejía 132
Applets
Son pequeñas aplicaciones que se
pueden ejecutar desde un visualizador del World Wide Web
![Page 133: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/133.jpg)
José Antonio García Mejía 133
Restricciones de Applets
• No pueden leer o escribir en el sistema de archivos del director.
• Sólo se pueden comunicar con el servidor donde residen.
• No pueden ejecutar ningún programa en el sistema del lector.
![Page 134: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/134.jpg)
José Antonio García Mejía 134
Creando Applets
public class myClass extends java.applet.Applet{
...}
![Page 135: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/135.jpg)
José Antonio García Mejía 135
Actividades principales de los applets
• Inicialización.
• Arranque.
• Detención.
• Destrucción.
![Page 136: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/136.jpg)
José Antonio García Mejía 136
Inicialización
public void init() {...
}
![Page 137: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/137.jpg)
José Antonio García Mejía 137
Arranque
public void start() {...
}
![Page 138: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/138.jpg)
José Antonio García Mejía 138
Detención
public void stop() {...
}
![Page 139: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/139.jpg)
José Antonio García Mejía 139
Destrucción
public void destroy() {
...}
![Page 140: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/140.jpg)
José Antonio García Mejía 140
Dibujo
public void paint(Graphics g) {...
}
![Page 141: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/141.jpg)
José Antonio García Mejía 141
Un Applet sencillo
1: import java.awt.Graphics;2: import java.awt.Font;3: import java.awt.Color;4:5: public class HelloAgainApplet
extends java.applet.Applet {6:7: Font f = new Font("TimesRoman",
Font.BOLD, 36);8:
![Page 142: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/142.jpg)
José Antonio García Mejía 142
Un applet sencillo
9: public void paint(Graphics g) {10: g.setFont(f);11: g.setColor(Color.red);12: g.drawString("Hello again!", 5, 40);13: }14: }
![Page 143: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/143.jpg)
José Antonio García Mejía 143
El tag <APPLET>1: <HTML>
2: <HEAD>3: <TITLE>This page has an applet on it</TITLE>4: </HEAD>5: <BODY>6: <P>My second Java applet says:7: <BR><APPLET CODE="HelloAgainApplet.class"
WIDTH=200 HEIGHT=50>8: Hello Again!9: </APPLET>10: </BODY>11: </HTML>
![Page 144: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/144.jpg)
José Antonio García Mejía 144
Resultado
![Page 145: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/145.jpg)
José Antonio García Mejía 145
Pasando parámetros a los Applets
1: <HTML>2: <HEAD>3: <TITLE>Hello!</TITLE>4: </HEAD>5: <BODY>6: <P>7: <APPLET CODE="MoreHelloApplet.class"
WIDTH=200 HEIGHT=50>8: <PARAM NAME=name VALUE="Bonzo">9: Hello to whoever you are!10: </APPLET>11: </BODY>12: </HTML>
![Page 146: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/146.jpg)
José Antonio García Mejía 146
Pasando parámetros a los Applets
1: import java.awt.Graphics;2: import java.awt.Font;3: import java.awt.Color;4:5: public class MoreHelloApplet extends
java.applet.Applet {6:7: Font f = new Font("TimesRoman",
Font.BOLD, 36);8: String name;9:
![Page 147: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/147.jpg)
José Antonio García Mejía 147
Pasando parámetros a los Applets
10: public void init() {11: name = getParameter("name");12: if (name == null)13: name = "Laura";14:15: name = "Hello " + name + "!";16: }17:
![Page 148: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/148.jpg)
José Antonio García Mejía 148
Pasando parámetros a los Applets
18: public void paint(Graphics g) {19: g.setFont(f);20: g.setColor(Color.red);21: g.drawString(name, 5, 40);22: }23: }
![Page 149: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/149.jpg)
José Antonio García Mejía 149
Resultado
![Page 150: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/150.jpg)
José Antonio García Mejía 150
La clase Graphics
import java.awt.Graphics;
public class MyClass extends java.applet.Applet {...}
![Page 151: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/151.jpg)
José Antonio García Mejía 151
El sistema coordenado
![Page 152: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/152.jpg)
José Antonio García Mejía 152
Líneas
import java.awt.Graphics;
public class MyLine extends java.applet.Applet {public void paint(Graphics g) {
g.drawLine(25,25,75,75);}
}
![Page 153: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/153.jpg)
José Antonio García Mejía 153
Resultado
![Page 154: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/154.jpg)
José Antonio García Mejía 154
Rectángulos
import java.awt.Graphics;
public class MyRect extends java.applet.Applet {public void paint(Graphics g) {
g.drawRect(20,20,60,60);g.fillRect(120,20,60,60);
}}
![Page 155: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/155.jpg)
José Antonio García Mejía 155
Resultado
![Page 156: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/156.jpg)
José Antonio García Mejía 156
Rectángulos redondeados
![Page 157: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/157.jpg)
José Antonio García Mejía 157
Rectángulos redondeados
import java.awt.Graphics;
public class MyRRect extendsjava.applet.Applet {
public void paint(Graphics g) {g.drawRoundRect(20,20,60,60,10,10);g.fillRoundRect(120,20,60,60,20,20);
}}
![Page 158: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/158.jpg)
José Antonio García Mejía 158
Resultado
Incluir la imagen para ejemplificar esto
![Page 159: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/159.jpg)
José Antonio García Mejía 159
Rectángulos 3D
import java.awt.Graphics;
public class My3DRect extends java.applet.Applet {public void paint(Graphics g) {
g.draw3DRect(20,20,60,60,true);g.draw3DRect(120,20,60,60,false);
}}
![Page 160: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/160.jpg)
José Antonio García Mejía 160
Resultado
Incluir la imagen para ejemplificar esto
![Page 161: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/161.jpg)
José Antonio García Mejía 161
Polígonos
import java.awt.Graphics;
public class MyPoly extends java.applet.Applet{
public void paint(Graphics g) {int exes[] = { 39,94,97,142,53,58,26 };int whys[] = { 33,74,36,70,108,80,106 };int pts = exes.length;
g.drawPolygon(exes,whys,pts);}
}
![Page 162: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/162.jpg)
José Antonio García Mejía 162
Resultado
![Page 163: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/163.jpg)
José Antonio García Mejía 163
Óvalos
import java.awt.Graphics;
public class MyOval extends java.applet.Applet {public void paint(Graphics g) {
g.drawOval(20,20,60,60);g.fillOval(120,20,100,60);
}}
![Page 164: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/164.jpg)
José Antonio García Mejía 164
Resultado
![Page 165: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/165.jpg)
José Antonio García Mejía 165
La clase Lamp1: import java.awt.*;2: 3: public class Lamp extends java.applet.Applet {4: 5: public void paint(Graphics g) {6: // the lamp platform7: g.fillRect(0,250,290,290);8:9: // the base of the lamp10: g.drawLine(125,250,125,160);11: g.drawLine(175,250,175,160);12:
![Page 166: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/166.jpg)
José Antonio García Mejía 166
La clase Lamp13: // the lamp shade, top and bottom edges14: g.drawArc(85,157,130,50,-65,312);15: g.drawArc(85,87,130,50,62,58);16: 17: // lamp shade, sides18: g.drawLine(85,177,119,89);19: g.drawLine(215,177,181,89);20: 21: // dots on the shade22: g.fillArc(78,120,40,40,63,-174);23: g.fillOval(120,96,40,40);24: g.fillArc(173,100,40,40,110,180);25: }26: }
![Page 167: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/167.jpg)
José Antonio García Mejía 167
Resultado
![Page 168: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/168.jpg)
José Antonio García Mejía 168
Texto y fuentes
1: import java.awt.Font;2: import java.awt.Graphics;3:4: public class ManyFonts extends java.applet.Applet {5:6: public void paint(Graphics g) {7: Font f = new Font("TimesRoman", Font.PLAIN, 18);8: Font fb = new Font("TimesRoman", Font.BOLD, 18);9: Font fi = new Font("TimesRoman", Font.ITALIC, 18);
10: Font fbi = new Font("TimesRoman", Font.BOLD + Font.ITALIC, 18);
![Page 169: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/169.jpg)
José Antonio García Mejía 169
Texto y fuentes12: g.setFont(f);13: g.drawString("This is a plain font", 10, 25);14: g.setFont(fb);15: g.drawString("This is a bold font", 10, 50);16: g.setFont(fi);17: g.drawString("This is an italic font", 10, 75);18: g.setFont(fbi);19: g.drawString("This is a bold italic font", 10, 100);20: }21:22: }
![Page 170: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/170.jpg)
José Antonio García Mejía 170
Texto y fuentes
![Page 171: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/171.jpg)
José Antonio García Mejía 171
Centrando un texto
1: import java.awt.Font;2: import java.awt.Graphics;3: import java.awt.FontMetrics;4:5: public class Centered extends
java.applet.Applet {6:7: public void paint(Graphics g) {8: Font f = new Font("TimesRoman",
Font.PLAIN, 36);9: FontMetrics fm = getFontMetrics(f);10: g.setFont(f);
![Page 172: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/172.jpg)
José Antonio García Mejía 172
Centrando un texto
11:12: String s = "This is how the world
ends.";13: int xstart = (size().width -
fm.stringWidth(s)) / 2;14: int ystart = size().height / 2;15:16: g.drawString(s, xstart, ystart);17: }18:}
![Page 173: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/173.jpg)
José Antonio García Mejía 173
Manejando colores
1: import java.awt.Graphics;2: import java.awt.Color;3:4: public class ColorBoxes extends java.applet.Applet {5:6: public void paint(Graphics g) {7: int rval, gval, bval;8:9: for (int j = 30; j < (size().height -25); j += 30)10: for (int i = 5; i < (size().width -25); i += 30) {11: rval = (int)Math.floor(Math.random() * 256);
![Page 174: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/174.jpg)
José Antonio García Mejía 174
Manejando colores
12: gval = (int)Math.floor(Math.random() * 256);
13: bval = (int)Math.floor(Math.random() * 256);
14:15: g.setColor(new Color(rval,gval,bval));16: g.fillRect(i, j, 25, 25);17: g.setColor(Color.black);18: g.drawRect(i-1, j-1, 25, 25);19: }20: }21: }
![Page 175: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/175.jpg)
José Antonio García Mejía 175
Resultado
![Page 176: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/176.jpg)
José Antonio García Mejía 176
Hilos
Son una secuencia de ejecución independiente de otras secuencias de ejecución o hilos que pudieran
existir.
![Page 177: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/177.jpg)
José Antonio García Mejía 177
Como escribir Applets con hilos
• Cambie la identificación de su clase applet para incluir las palabras implements Runnable.
• Incluya una variable de instancia para guardar el hilo.
![Page 178: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/178.jpg)
José Antonio García Mejía 178
Como escribir Applets con hilos
• Modifique el método start() para producir un hilo e iniciar su ejecución.
• Cree el método run() que contenga el código actual que inicie la ejecución de su applet.
![Page 179: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/179.jpg)
José Antonio García Mejía 179
Un reloj Digital1: import java.awt.Graphics;2: import java.awt.Font;3: import java.util.Date;4:5: public class DigitalClock extends
java.applet.Applet 6: implements Runnable {7: 8: Font theFont = new
Font("TimesRoman",Font.BOLD,24);9: Date theDate;10: Thread runner;
![Page 180: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/180.jpg)
José Antonio García Mejía 180
Un reloj Digital12: public void start() {13: if (runner == null) {14: runner = new Thread(this);15: runner.start();16: }17: }18:19: public void stop() {20: if (runner != null) {21: runner.stop();21: runner = null;22: }23: }
![Page 181: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/181.jpg)
José Antonio García Mejía 181
Un reloj Digital25: public void run() {26: while (true) {27: theDate = new Date();28: repaint();29: try { Thread.sleep(1000); }30: catch (InterruptedException e) { }31: }32: }33: 34: public void paint(Graphics g) {35: g.setFont(theFont);36: g.drawString(theDate.toString(),10,50);37: }38:}
![Page 182: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/182.jpg)
José Antonio García Mejía 182
El método repaint()
• La llamada a repaint() resulta en una llamada al método update().
• El método update() limpia el contenido existente en la pantalla y luego llama a paint().
• El método paint() dibuja el contenido del cuadro actual.
![Page 183: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/183.jpg)
José Antonio García Mejía 183
Evitando el parpadeo en los Applets
Sobreponga update() para no borrar nada en la pantalla o para borrar sólo las partes de la
pantalla que usted cambió.
public void update(Graphics g) {g.setColor(getBackground());g.fillRect(0, 0, width, height);g.setColor(getForeground());paint(g);
}
![Page 184: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/184.jpg)
José Antonio García Mejía 184
Uso de Imágenes
La clase Image en java.awt ofrece métodos abstractos para
representar un comportamiento de imagen común y métodos
especiales definidos en Applet yGraphics para desplegarlas y
usarlas en sus applets.
![Page 185: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/185.jpg)
José Antonio García Mejía 185
Obteniendo ImágenesImage img = getImage(
newURL("http://www.server.com/files/image.gif"));
Image img = getImage(getDocumentBase(), "image.gif")
Image img = getImage(getCodeBase(), "image.gif")
Image img = getImage(getCodeBase(), "images/image.gif")
![Page 186: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/186.jpg)
José Antonio García Mejía 186
Desplegando Imágenes
public void paint() {g.drawImage(img, 10, 10, this);
}
![Page 187: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/187.jpg)
José Antonio García Mejía 187
El Applet Ladybug
1:import java.awt.Graphics;2:import java.awt.Image;3:4:public class LadyBug extends
java.applet.Applet {5:6: Image bugimg;7:8: public void init() {9: bugimg = getImage(getCodeBase(),10: "images/ladybug.gif");11: }
![Page 188: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/188.jpg)
José Antonio García Mejía 188
EL Applet Ladybug
12:13: public void paint(Graphics g) {14: g.drawImage(bugimg, 10, 10,this);15: }16:}
![Page 189: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/189.jpg)
José Antonio García Mejía 189
El Applet Ladybug
![Page 190: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/190.jpg)
José Antonio García Mejía 190
El Applet Ladybug21: import java.awt.Graphics;2: import java.awt.Image;3:4: public class LadyBug2 extends java.applet.Applet {5:6: Image bugimg;7:8: public void init() {9: bugimg = getImage(getCodeBase(),10: "images/ladybug.gif");11: }
![Page 191: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/191.jpg)
José Antonio García Mejía 191
El Applet Ladybug213: public void paint(Graphics g) {14: int iwidth = bugimg.getWidth(this);15: int iheight = bugimg.getHeight(this);16: int xpos = 10;17:18: // 25 %19: g.drawImage(bugimg, xpos, 10,20: iwidth / 4, iheight / 4, this);21:22: // 50 %23: xpos += (iwidth / 4) + 10;24: g.drawImage(bugimg, xpos , 10,25: iwidth / 2, iheight / 2, this);
![Page 192: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/192.jpg)
José Antonio García Mejía 192
El Applet Ladybug2
27: // 100%28: xpos += (iwidth / 2) + 10;29: g.drawImage(bugimg, xpos, 10, this);30:31: // 150% x, 25% y32: g.drawImage(bugimg, 10, iheight + 30,33: (int)(iwidth * 1.5), iheight / 4, this);34: }35: }
![Page 193: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/193.jpg)
José Antonio García Mejía 193
EL APPLET neko
![Page 194: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/194.jpg)
José Antonio García Mejía 194
Eventos
Es la manera en la cual el AWT le comunica a usted y a otros
componentes Java AWT que algoha sucedido
![Page 195: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/195.jpg)
José Antonio García Mejía 195
Algunos eventos sencillos
• Clics del mouse.
• Movimientos del mouse.
• Eventos del teclado.
![Page 196: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/196.jpg)
José Antonio García Mejía 196
Clicks del Mouse
• mouseDown().
• mouseUp().
• mouseDrag().
• mouseMove().
![Page 197: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/197.jpg)
José Antonio García Mejía 197
mouseDown()
public boolean mouseDown(Event evt, int x, int y) {...}
![Page 198: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/198.jpg)
José Antonio García Mejía 198
mouseUp()
public boolean mouseUp(Event evt, int x, int y) {...}
![Page 199: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/199.jpg)
José Antonio García Mejía 199
El Applet Spots1: import java.awt.Graphics;2: import java.awt.Color;3: import java.awt.Event;4:5: public class Spots extends
java.applet.Applet {6:7: final int MAXSPOTS = 10;8: int xspots[] = new int[MAXSPOTS];9: int yspots[] = new int[MAXSPOTS];10: int currspots = 0;
![Page 200: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/200.jpg)
José Antonio García Mejía 200
EL Applet Spots12: public void init() {13: setBackground(Color.white);14: }15:16: public boolean mouseDown(Event evt, int x,
int y) {17: if (currspots < MAXSPOTS) {18: addspot(x,y);19: return true;20: }21: else {22: System.out.println("Too many spots.");23: return false;24: }25: }
![Page 201: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/201.jpg)
José Antonio García Mejía 201
EL Applet Spots27: void addspot(int x,int y) {28: xspots[currspots] = x;29: yspots[currspots] = y;30: currspots++;31: repaint();32: }33: 34: public void paint(Graphics g) {35: g.setColor(Color.blue);36: for (int i = 0; i < currspots; i++) {37: g.fillOval(xspots[i] - 10, yspots[i] - 10, 20,
20);38: }39: }40: }
![Page 202: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/202.jpg)
José Antonio García Mejía 202
EL APPLET SPOTS
![Page 203: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/203.jpg)
José Antonio García Mejía 203
DOBLE CLIC
public boolean mouseDown(Event evt, int x, int y) {switch (evt.clickCount) {case 1: // single-clickcase 2: // double-clickcase 3: // triple-click....
}
![Page 204: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/204.jpg)
José Antonio García Mejía 204
MOVIMIENTOS DEL MOUSE
• mouseDrag().
• mouseMove().
![Page 205: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/205.jpg)
José Antonio García Mejía 205
mouseDrag()
public boolean mouseDrag(Event evt, int x, int y) {...}
![Page 206: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/206.jpg)
José Antonio García Mejía 206
mouseMove()
public boolean mouseMove(Event evt, int x, int y) {...}
![Page 207: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/207.jpg)
José Antonio García Mejía 207
ENTRADA Y SALIDA DEL APPLET
• mouseEnter().
• mouseExit().
![Page 208: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/208.jpg)
José Antonio García Mejía 208
mouseEnter()
public boolean mouse Enter(Event evt, int x, int y) {...}
![Page 209: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/209.jpg)
José Antonio García Mejía 209
mouseExit()
public boolean mouseExit(Event evt, int x, int y) {...}
![Page 210: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/210.jpg)
José Antonio García Mejía 210
EL APPLET Lines1: import java.awt.Graphics;2: import java.awt.Color;3: import java.awt.Event;4: import java.awt.Point;5:6: public class Lines extends java.applet.Applet {7:8: final int MAXLINES = 10;9: Point starts[] = new Point[MAXLINES]; // starting
points10: Point ends[] = new Point[MAXLINES]; //
endingpoints11: Point anchor; // start of current line12: Point currentpoint; // current end of line13: int currline = 0; // number of lines
![Page 211: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/211.jpg)
José Antonio García Mejía 211
EL APPLET Lines15: public void init() {16: setBackground(Color.white);17: }18:19: public boolean mouseDown(Event evt, int x, int
y) {20: if (currline < MAXLINES) {21: anchor = new Point(x,y);22: return true;23: }24: else {25: System.out.println("Too many lines.");26: return false;27: }28: }
![Page 212: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/212.jpg)
José Antonio García Mejía 212
EL APPLET Lines30: public boolean mouseUp(Event evt, int x, int y) {
31: if (currline < MAXLINES) {32: addline(x,y);33: return true;34: }35: else return false;36: }37: 38: public boolean mouseDrag(Event evt, int x, int y) {39: if (currline < MAXLINES) {40: currentpoint = new Point(x,y);41: repaint();42: return true;43: }44: else return false;45: }
![Page 213: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/213.jpg)
José Antonio García Mejía 213
EL APPLET Lines
46:47: void addline(int x,int y) {48: starts[currline] = anchor;49: ends[currline] = new Point(x,y);50: currline++;51: currentpoint = null;52: anchor = null;53: repaint();54: }55:
![Page 214: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/214.jpg)
José Antonio García Mejía 214
EL APPLET Lines56: public void paint(Graphics g) {57: 58: // Draw existing lines59: for (int i = 0; i < currline; i++) {60: g.drawLine(starts[i].x, starts[i].y,61: ends[i].x, ends[i].y);62: }63: 64: // draw current line65: g.setColor(Color.blue);66: if (currentpoint != null)67: g.drawLine(anchor.x,anchor.y,68: currentpoint.x,currentpoint.y);69: }70:}
![Page 215: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/215.jpg)
José Antonio García Mejía 215
EL APPLET Lines
![Page 216: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/216.jpg)
José Antonio García Mejía 216
EVENTOS DEL TECLADO
public boolean keyDown(Event evt, int key) {...
}
public boolean keyDown(Event evt, int key) {System.out.println("ASCII value: " + key);System.out.println("Character: " + (char)key);return true;
}
![Page 217: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/217.jpg)
José Antonio García Mejía 217
EVENTOS DEL TECLADO
public boolean keyUp(Event evt, int key) {...
}
![Page 218: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/218.jpg)
José Antonio García Mejía 218
EL APPLET Keys1: import java.awt.Graphics;2: import java.awt.Event;3: import java.awt.Font;4: import java.awt.Color;5: 6: public class Keys extends
java.applet.Applet {7: 8: char currkey;9: int currx;10: int curry;
![Page 219: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/219.jpg)
José Antonio García Mejía 219
EL APPLET Keys
12: public void init() {13: currx = (size().width / 2) -8; // default14: curry = (size().height / 2) -16;15:16: setBackground(Color.white);17: setFont(new
Font("Helvetica",Font.BOLD,36));18: }
![Page 220: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/220.jpg)
José Antonio García Mejía 220
EL APPLET Keys
20: public boolean keyDown(Event evt, int key) {
21: switch (key) {22: case Event.DOWN:23: curry += 5;24: break;25: case Event.UP:26: curry -= 5;27: break;
![Page 221: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/221.jpg)
José Antonio García Mejía 221
EL APPLET Keys
28: case Event.LEFT:29: currx -= 5;30: break;31: case Event.RIGHT:32: currx += 5;33: break;34: default:35: currkey = (char)key;36: }37:38: repaint();39: return true;40: }
![Page 222: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/222.jpg)
José Antonio García Mejía 222
EL APPLET Keys
42: public void paint(Graphics g) {43: if (currkey != 0) {44:
g.drawString(String.valueOf(currkey), currx,curry);
45: }46: }47: }
![Page 223: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/223.jpg)
José Antonio García Mejía 223
PROBANDO LAS TECLAS MODIFICADORES
Permite verificar las teclas de control y meta (Alt)
public boolean mouseDown(Event evt, int x, int y ) {if (evt.shiftDown())
// handle shift-clickelse // handle regular click
}
![Page 224: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/224.jpg)
José Antonio García Mejía 224
PROBANDO LAS TECLAS MODIFICADORES
public boolean mouseDown(Event evt, int x, inty ) {
if (evt.metaDown())// handle a right-click
else if (evt.controlDown())// handle a middle-click
else // handle a regular click}
![Page 225: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/225.jpg)
José Antonio García Mejía 225
EL MANEJADOR DE EVENTOS AWT
public boolean handleEvent(Event evt) {switch (evt.id) {case Event.MOUSE_DOWN:
System.out.println("MouseDown: " +evt.x + "," + evt.y);
return true;case Event.MOUSE_UP:
System.out.println("MouseUp: " +evt.x + "," + evt.y);
return true;
![Page 226: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/226.jpg)
José Antonio García Mejía 226
EL MANEJADOR DE EVENTOS AWT
case Event.MOUSE_MOVE:
System.out.println("MouseMove: " +evt.x + "," + evt.y);
return true;case Event.MOUSE_DRAG:
System.out.println("MouseDrag: " +evt.x + "," + evt.y);
return true;default:
return false;}
}
![Page 227: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/227.jpg)
José Antonio García Mejía 227
OBJETIVO
Conocer los elementos fundamentales para el manejo del
AWT en Java
![Page 228: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/228.jpg)
José Antonio García Mejía 228
EL AWT OFRECE
•Un conjunto completo de accesorios UI.
•Respaldo para contenedores UI.•Un sistema de eventos.•Mecanismos para distribuir los componentes de forma que permitan un diseño UI independiente de la plataforma.
![Page 229: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/229.jpg)
José Antonio García Mejía 229
IDEA BÁSICA
Una ventana Java es un conjunto de componentes anidados que
empieza desde la ventana exterior hasta el más pequeño
componente UI.
![Page 230: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/230.jpg)
José Antonio García Mejía 230
COMPONENTES AWT
![Page 231: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/231.jpg)
José Antonio García Mejía 231
PRINCIPALES COMPONENTES
• Contenedores.
• Lienzos.
• Componentes UI.
• Componentes de construcción de ventana.
![Page 232: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/232.jpg)
José Antonio García Mejía 232
JERARQUÍA DE CLASES AWT PARCIAL
![Page 233: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/233.jpg)
José Antonio García Mejía 233
COMPONENTES BÁSICOS DE LA UI
public void init() {Button b = new Button("OK");add(b);
}
![Page 234: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/234.jpg)
José Antonio García Mejía 234
ETIQUETAS
Son cadenas de texto que puede usar para etiquetar otros componentes
•Label()
•Label(String)
•Label(String,int)
![Page 235: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/235.jpg)
José Antonio García Mejía 235
ETIQUETASimport java.awt.*;
public class LabelTest extends java.applet.Applet {
public void init() {setFont(new Font ("Helvetica", Font.BOLD, 14));setLayout(new GridLayout(3,1));add(new Label("aligned left", Label.LEFT));add(new Label("aligned center",
Label.CENTER));add(new Label("aligned right", Label.RIGHT));
}}
![Page 236: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/236.jpg)
José Antonio García Mejía 236
BOTONES
Son componentes UI sencillos que inician alguna acción cuando se les
oprime
•Button().
•Button(String).
![Page 237: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/237.jpg)
José Antonio García Mejía 237
BOTONESpublic class ButtonTest extends java.applet.Applet {
public void init() {add(new Button("Rewind"));add(new Button("Play"));add(new Button("Fast Forward"));add(new Button("Stop"));
}}
![Page 238: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/238.jpg)
José Antonio García Mejía 238
CASILLAS DE VERIFICACIÓN
Son componentes que tienen dos estados:activada o desactivada. No inician acciones directas en la UI,
pero, en su lugar, se usan para indicar características opcionales de
alguna otra acción
![Page 239: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/239.jpg)
José Antonio García Mejía 239
CASILLAS DE VERIFICACIÓN
•Checbox( ).
•Checbox(String).
•Checbox(String, null, boolean).
![Page 240: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/240.jpg)
José Antonio García Mejía 240
CASILLAS DE VERIFICACIÓN
import java.awt.*;
public class CheckboxTest extends java.applet.Applet{
public void init() {setLayout(new FlowLayout(FlowLayout.LEFT));add(new Checkbox("Shoes"));add(new Checkbox("Socks"));add(new Checkbox("Pants"));add(new Checkbox("Underwear", null, true));add(new Checkbox("Shirt"));
}}
![Page 241: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/241.jpg)
José Antonio García Mejía 241
BOTONES DE RADIO
Tienen la misma apariencia de las casillas de verificación, pero sólo uno
de una serie de ellos puede seleccionarse a la vez.
![Page 242: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/242.jpg)
José Antonio García Mejía 242
BOTONES DE RADIOimport java.awt.*;
public class CheckboxGroupTest extendsjava.applet.Applet {
public void init() {setLayout(new FlowLayout(FlowLayout.LEFT));CheckboxGroup cbg = new CheckboxGroup();
add(new Checkbox("Red", cbg, false));add(new Checkbox("Blue", cbg, false));add(new Checkbox("Yellow", cbg, false));add(new Checkbox("Green", cbg, true));add(new Checkbox("Orange", cbg, false));add(new Checkbox("Purple", cbg, false));
}}
![Page 243: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/243.jpg)
José Antonio García Mejía 243
MENÚS DE OPCIONES
Permiten seleccionar un elemento de un menú que se despliega en pantalla
![Page 244: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/244.jpg)
José Antonio García Mejía 244
MENÚS DE OPCIONESimport java.awt.*;
public class ChoiceTest extendsjava.applet.Applet {
public void init() {Choice c = new Choice();c.addItem("Apples");c.addItem("Oranges");c.addItem("Strawberries");c.addItem("Blueberries");c.addItem("Bananas");add(c);
}}
![Page 245: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/245.jpg)
José Antonio García Mejía 245
CAMPOS DE TEXTO
Permiten al lector introducir texto
•Textfield().
•Textfield(int).
•Textfield(String).
•Textfield(String,int).
![Page 246: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/246.jpg)
José Antonio García Mejía 246
CAMPOS DE TEXTO
add(new Label("Enter your Name"));add(new TextField("your name here", 45));add(new Label("Enter your phone number"));add(new TextField(12));add(new Label("Enter your password"));TextField t = new TextField(20);t.setEchoCharacter('*');add(t);
![Page 247: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/247.jpg)
José Antonio García Mejía 247
ADMINISTRADORES DE DISEÑO
Determina la forma en la cual los componentes AWT se muestran en la pantalla.
![Page 248: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/248.jpg)
José Antonio García Mejía 248
LA CLASE FlowLayoutimport java.awt.*;
public class FlowLayoutTest extendsjava.applet.Applet {
public void init() {setLayout(new FlowLayout());add(new Button("One"));add(new Button("Two"));add(new Button("Three"));add(new Button("Four"));add(new Button("Five"));add(new Button("Six"));
}}
![Page 249: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/249.jpg)
José Antonio García Mejía 249
LA CLASE GridLayoutimport java.awt.*;
public class GridLayoutTest extendsjava.applet.Applet {
public void init() {setLayout(new GridLayout(3,2);add(new Button("One"));add(new Button("Two"));add(new Button("Three"));add(new Button("Four"));add(new Button("Five"));add(new Button("Six"));
}}
![Page 250: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/250.jpg)
José Antonio García Mejía 250
LA CLASE BorderLayoutimport java.awt.*;
public class BorderLayoutTest extendsjava.applet.Applet {
public void init() {setLayout(new BorderLayout());add("North", new Button("One"));add("East", new Button("Two"));add("South", new Button("Three"));add("West", new Button("Four"));add("Center", new Button("Five"));add(new Button("Six"));
}}
![Page 251: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/251.jpg)
José Antonio García Mejía 251
MANEJO DE ACCIONES Y EVENTOS UI
public boolean action(Event evt, Object arg) {...
}
![Page 252: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/252.jpg)
José Antonio García Mejía 252
MANEJO DE ACCIONES Y EVENTOS UI
Todos los componentes UI básicos cuentan con diferentes acciones y argumentos:
•El argumento de un botón es la etiqueta del botón.
•Las casillas de verificación, exclusivas y no exclusivas, generan acciones cuando se seleccionan. El argumento es siempre true.
![Page 253: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/253.jpg)
José Antonio García Mejía 253
MANEJO DE ACCIONES Y EVENTOS UI
•Los campos de texto crean acciones cuando el usuario presiona Return dentro del campo de texto.
![Page 254: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/254.jpg)
José Antonio García Mejía 254
MANEJO DE ACCIONES Y EVENTOS UI
public boolean action(Event evt, Object arg) {if (evt.target instanceof TextField)
return handleText(evt.target);else if (evt.target instanceof Choice)
return handleChoice(arg);...}
![Page 255: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/255.jpg)
José Antonio García Mejía 255
MANEJO DE ACCIONES Y EVENTOS UI
1:import java.awt.*;3:public class ButtonActionsTest extends
java.applet.Applet {4:5: public void init() {6: setBackground(Color.white);7:8: add(new Button("Red"));9: add(new Button("Blue"));10: add(new Button("Green"));11: add(new Button("White"));12: add(new Button("Black"));13: }
![Page 256: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/256.jpg)
José Antonio García Mejía 256
MANEJO DE ACCIONES Y EVENTOS UI
15: public boolean action(Event evt, Object arg) {
16: if (evt.target instanceof Button) {17: changeColor((String)arg);18: return true;19: } else return false;20: }
![Page 257: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/257.jpg)
José Antonio García Mejía 257
MANEJO DE ACCIONES Y EVENTOS UI
22: void changeColor(String bname) {23: if (bname.equals("Red")) setBackground(Color.red);24: else if (bname.equals("Blue"))
setBackground(Color.blue);25: else if (bname.equals("Green"))
setBackground(Color.green);26: else if (bname.equals("White"))
setBackground(Color.white);27: else setBackground(Color.black);28:29: repaint();30: }31:}
![Page 258: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/258.jpg)
José Antonio García Mejía 258
ANIDANDO PANELES Y COMPONENTES
Permite crear diferentes diseños para distintas partes generales del
área general del applet, aislar colores de fondo y primer plano y fuentes a partes individuales de un applet.
![Page 259: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/259.jpg)
José Antonio García Mejía 259
ANIDANDO PANELES Y COMPONENTES
setLayout(new GridLayout(1, 2, 10, 10));Panel panel1 = new Panel();Panel panel2 = new Panel();add(panel1);add(panel2);
![Page 260: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/260.jpg)
José Antonio García Mejía 260
ANIDANDO PANELES Y COMPONENTES
panel1.setLayout(new FlowLayout());panel1.add(new Button("Up"));panel1.add(new Button("Down"));
![Page 261: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/261.jpg)
José Antonio García Mejía 261
EVENTOS Y PANELES ANIDADOS
Al crear un applet con paneles anidados, los paneles forman una jerarquía desde el panel más externo hasta el componente
UI más interno.Esta jerarquía afecta el manejo de
eventos. Los eventos son recibido por el componente más interno y son
trasladados en cadena hacia la raíz.
![Page 262: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/262.jpg)
José Antonio García Mejía 262
EVENTOS Y PANELES ANIDADOS
Un método de manejo de eventos, ya sea los métodos de eventos básicos
(mouseDown, mouseUp) o el más genérico puede realizar una de tres tareas
posibles:
![Page 263: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/263.jpg)
José Antonio García Mejía 263
EVENTOS Y PANELES ANIDADOS
•No estar interesado en el evento. El evento se pasa hacia arriba en la jerarquía hasta que un componente lo procese. El método de manejo de eventos debe regresar false.
![Page 264: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/264.jpg)
José Antonio García Mejía 264
EVENTOS Y PANELES ANIDADOS
•Interceptar el evento, procesarlo y regresar true. En este caso, el evento se detiene en ese método.
![Page 265: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/265.jpg)
José Antonio García Mejía 265
EVENTOS Y PANELES ANIDADOS
•Interceptar el método, procesarlo y pasarlo al siguiente manejador de eventos.
![Page 266: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/266.jpg)
José Antonio García Mejía 266
OTROS COMPONENTES UI
•Áreas de texto.
•Listas desplazables.
•Barras de desplazamiento.
•Deslizadores.
![Page 267: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/267.jpg)
José Antonio García Mejía 267
ÁREAS DE TEXTO
Permite la introducción de grandes cantidades de texto.
•TextArea().
•TextArea(int,int).
•TextArea(String).
•TextArea(String,int,int).
![Page 268: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/268.jpg)
José Antonio García Mejía 268
ÁREAS DE TEXTOimport java.awt.*;
public class TextAreaTest extendsjava.applet.Applet {
public void init() {String str = ”Esta es una prueba de un
área de texto";// more text deleted for space
add(new TextArea(str,10,50));}
}
![Page 269: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/269.jpg)
José Antonio García Mejía 269
LISTAS DESPLAZABLES
Es similar a un menú de opciones que permite escoger varias opciones
de una lista
•List()
•List(int, boolean).
![Page 270: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/270.jpg)
José Antonio García Mejía 270
LISTAS DESPLAZABLESimport java.awt.*;public class ListsTest extends
java.applet.Applet {public void init() {List lst = new List(5, true);lst.addItem("Hamlet");lst.addItem("Claudius");lst.addItem("Gertrude");lst.addItem("Polonius");lst.addItem("Horatio");lst.addItem("Laertes");lst.addItem("Ophelia");add(lst);
}}
![Page 271: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/271.jpg)
José Antonio García Mejía 271
BARRAS DE DESPLAZAMIENTO
Permiten seleccionar un valor entre un valor máximo y uno mínimo.
•Scrollbar().
•Scrollbar(int).
•Scrollbar(int,int,int,int)
![Page 272: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/272.jpg)
José Antonio García Mejía 272
BARRAS DE DESPLAZAMIENTOimport java.awt.*;
public class SliderTest extendsjava.applet.Applet {
Label l;
public void init() {setLayout(new GridLayout(1,2));l = new Label("0", Label.CENTER);add(l);add(new
Scrollbar(Scrollbar.HORIZONTAL,0,0,1,100));}
![Page 273: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/273.jpg)
José Antonio García Mejía 273
BARRAS DE DESPLAZAMIENTO
public Insets insets() {return new Insets(15,15,15,15);
}public boolean handleEvent(Event evt) {if (evt.target instanceof Scrollbar) {int v = ((Scrollbar)evt.target).getValue();l.setText(String.valueOf(v));repaint();return true;
} else return false;}
}
![Page 274: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/274.jpg)
José Antonio García Mejía 274
CANVAS
Es un componentes sobre el que se puede dibujar
Canvas can = new Canvas();add(can);
![Page 275: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/275.jpg)
José Antonio García Mejía 275
MAS EVENTOS UI
Para eventos relacionados con las barras de desplazamiento y las listas
desplazables, la única manera de interceptar estos eventos es sobreponer handleEvent( )
![Page 276: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/276.jpg)
José Antonio García Mejía 276
EL AWT OFRECE
•Ventanas.•Menús.•Cuadros de diálogo.
![Page 277: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/277.jpg)
José Antonio García Mejía 277
CLASE WINDOW DEL AWT
![Page 278: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/278.jpg)
José Antonio García Mejía 278
FRAMES
Permite crear una ventana funcional completa con una barra de menús.
•Frame
•Frame(String)
![Page 279: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/279.jpg)
José Antonio García Mejía 279
UNA VENTANA POP-UP1:import java.awt.*;2:3:public class PopupWindow extends
java.applet.Applet {4: Frame window;5:6: public void init() {7: add(new Button("Open Window"));8: add(new Button("Close Window"));9:10: window = new BaseFrame("A Popup
Window");11: window.resize(150,150);12: window.show();13: }
![Page 280: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/280.jpg)
José Antonio García Mejía 280
UNA VENTANA POP-UP15: public boolean action(Event evt, Object arg) {16: if (evt.target instanceof Button) {17: String label = (String)arg;18: if (label.equals("Open Window")) {19: if (!window.isShowing()) 20: window.show();21: }22: else if (label.equals("Close Window")) {23: if (window.isShowing())24: window.hide();25: }26: return true;27: } 28: else return false;29: }30:}
![Page 281: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/281.jpg)
José Antonio García Mejía 281
LA CLASE BASEFRAME1:import java.awt.*;2:3:class BaseFrame extends Frame {4: String message = "This is a Window";5:6: BaseFrame1(String title) {7: super(title);8: setFont(new Font("Helvetica", Font.BOLD,
12));9: }10:11: public void paint(Graphics g) {12: g.drawString(message, 20, 20);13: }14:}
![Page 282: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/282.jpg)
José Antonio García Mejía 282
CERRANDO LA VENTANA
Agregue el siguiente método para poder cerrar la ventana
public boolean handleEvent(Event evt) {if (evt.id == Event.WINDOW_DESTROY) hide();return super.handleEvent(evt);
}
![Page 283: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/283.jpg)
José Antonio García Mejía 283
MENÚS Y BARRAS DE MENÚS
![Page 284: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/284.jpg)
José Antonio García Mejía 284
MENÚS Y BARRAS DE MENÚS
1:import java.awt.*;2:3:class BaseFrame2 extends Frame {4: String message = "This is a Window";5:6: BaseFrame2(String title) {7: super(title);8: setFont(new Font("Helvetica", Font.BOLD, 12));9:
![Page 285: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/285.jpg)
José Antonio García Mejía 285
MENÚS Y BARRAS DE MENÚS
10: MenuBar mb = new MenuBar();11: Menu m = new Menu("Colors");12: m.add(new MenuItem("Red"));13: m.add(new MenuItem("Blue"));14: m.add(new MenuItem("Green"));15: m.add(new MenuItem("-"));16: m.add(new CheckboxMenuItem("Reverse Text"));17: mb.add(m);18: setMenuBar(mb);19: }
![Page 286: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/286.jpg)
José Antonio García Mejía 286
MENÚS Y BARRAS DE MENÚS21: public boolean action(Event evt, Object arg) {
22: String label = (String)arg;23: if (evt.target instanceof MenuItem) {24: if (label.equals("Red")) setBackground(Color.red);25: else if (label.equals("Blue"))
setBackground(Color.blue);26: else if (label.equals("Green"))
setBackground(Color.green);27: else if (label.equals("Reverse Text")) {28: if (getForeground() == Color.black) {29: setForeground(Color.white);30: } else setForeground(Color.black);31: }32: repaint();33: return true;34: } else return false;35: }
![Page 287: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/287.jpg)
José Antonio García Mejía 287
MENÚS Y BARRAS DE MENÚS
37: public void paint(Graphics g) {38: g.drawString(message, 20, 20);39: }40:41: public boolean handleEvent(Event evt) {42: if (evt.id == Event.WINDOW_DESTROY)
hide();43: return super.handleEvent(evt);44: }45:}
![Page 288: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/288.jpg)
José Antonio García Mejía 288
DIÁLOGOS
Tienen una función similar a los frames, sin embargo, están destinados a emplearse como
ventanas transitorias, ventanas que le permiten
conocer advertencias, solicitan información
específica, etc.
![Page 289: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/289.jpg)
José Antonio García Mejía 289
DIÁLOGOS
Para agregar un diálogo de texto en la clase BaseFrame,
agregue :
TextDialog dl;
![Page 290: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/290.jpg)
José Antonio García Mejía 290
DIÁLOGOS
Para agregar un diálogo de texto en la clase BaseFrame, agregue al
constructor:
m.add(new CheckboxMenuItem("Reverse Text"));
m.add(new MenuItem("Set Text..."));
![Page 291: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/291.jpg)
José Antonio García Mejía 291
DIÁLOGOS
Para agregar un diálogo de texto en la clase BaseFrame, agregue al
constructor:
dl = new TextDialog(this, "Enter Text", true);dl.resize(150,100);
![Page 292: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/292.jpg)
José Antonio García Mejía 292
DIÁLOGOS
Para agregar un diálogo de texto en la clase BaseFrame, agregue al método
action():
else if (label.equals("Green")) setBackground(Color.green);
else if (label.equals("Set Text...")) dl.show();else if (label.equals("Reverse Text")) {
![Page 293: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/293.jpg)
José Antonio García Mejía 293
LA CLASE TextDialog( )
1:import java.awt.*;2:3:class TextDialog extends Dialog {4: TextField tf;5: BaseFrame3 theFrame;
![Page 294: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/294.jpg)
José Antonio García Mejía 294
LA CLASE TextDialog( )
7: TextDialog(Frame parent, String title, boolean modal) {
8: super(parent, title, modal);9:10: theFrame = (BaseFrame3)parent;11: setLayout(new BorderLayout(10,10));12: setBackground(Color.white);13: tf = new
TextField(theFrame.message,20);14: add("Center", tf);15: add("South", new Button("OK"));16: resize(150,75);17: }
![Page 295: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/295.jpg)
José Antonio García Mejía 295
LA CLASE TextDialog( )19: public Insets insets() {20: return new Insets(30,10,10,10);21: }23: public boolean action(Event evt, Object
arg) {24: String label = (String)arg;25: if (evt.target instanceof Button) {26: if (label == "OK") {27: hide();28: theFrame.message = tf.getText();29: theFrame.repaint();30: }}32: else return false;33: return true;34: } }
![Page 296: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/296.jpg)
José Antonio García Mejía 296
DIÁLOGOS DE ARCHIVO
Es un cuadro de diálogo básico para abrir y (o) guardar
archivos, el cual le permite tener acceso al sistema de
archivos de la plataforma sobre la cual ejecuta la aplicación
Java.
![Page 297: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/297.jpg)
José Antonio García Mejía 297
DIÁLOGOS DE ARCHIVO
•FileDialog(Frame,String)
•FileDialog(Frame,String,int)
![Page 298: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/298.jpg)
José Antonio García Mejía 298
DIÁLOGOS DE ARCHIVO
FileDialog fd = new FileDialog(this, "FileDialog");
fd.show();
![Page 299: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/299.jpg)
José Antonio García Mejía 299
JDBC
•Creado por Hughes Technologies en Australia.
•DBMS light para UNIX accesible por Internet.
•Orientado a Intranet’s.
![Page 300: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/300.jpg)
José Antonio García Mejía 300
Java Networking
Java posee clases para la construcción
de aplicaciones cliente-servidor
![Page 301: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/301.jpg)
José Antonio García Mejía 301
Java Networking
Las clases están orientadas a utilizar
los servicios que ofrece TCP/IP
![Page 302: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/302.jpg)
José Antonio García Mejía 302
Paquete
java.net.*;
![Page 303: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/303.jpg)
José Antonio García Mejía 303
TIPOS DE APLICACIONES
•Socket API.•URL’s
![Page 304: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/304.jpg)
José Antonio García Mejía 304
SOCKET’S
Interface de bajo nivel para comunicaciones
en red
![Page 305: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/305.jpg)
José Antonio García Mejía 305
TIPOS DE SOCKET’S
•Orientados a la conexión (TCP).
•Sin conexión (UDP).
![Page 306: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/306.jpg)
José Antonio García Mejía 306
CLIENTES Y SERVIDORES
El cliente es quien inicia la conversión creando un
socket.
![Page 307: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/307.jpg)
José Antonio García Mejía 307
CLIENTES Y SERVIDORES
El servidor se debe preparar para escuchar
las comunicaciones entrantes
![Page 308: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/308.jpg)
José Antonio García Mejía 308
PROTOCOLOS
Es el conjunto de reglas que gobiernan el
comportamiento de una red
![Page 309: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/309.jpg)
José Antonio García Mejía 309
TIPOS DE PROTOCOLOS
•Telnet
•SMTP
•FTP
•HTTP
![Page 310: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/310.jpg)
José Antonio García Mejía 310
PROTOCOLO SMTP
HELO host.dominio.nombre
MAIL FROM:usuario@direccion
RCPTTO:usuario@direccion
![Page 311: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/311.jpg)
José Antonio García Mejía 311
PROTOCOLO SMTP
DATA
(mensaje de correo)
.
QUIT
![Page 312: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/312.jpg)
José Antonio García Mejía 312
JDBC
Es una API de Java para ejecutar
estatutos de SQL a prácticamente
cualquier base de datos relacional.
![Page 313: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/313.jpg)
José Antonio García Mejía 313
JDBCProvee una API
estándar que posibilita la escritura de aplicaciones de
base de datos utilizando Java
![Page 314: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/314.jpg)
José Antonio García Mejía 314
JDBCCon Java y JDBC es posible publicar una
página Web conteniendo applets que accedan a bases
de datos
![Page 315: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/315.jpg)
José Antonio García Mejía 315
JDBCLas empresas pueden continuar utilizando sus
bases de datos instaladas y pueden acceder a
información aún si están almacenadas en diferentes
DBMS
![Page 316: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/316.jpg)
José Antonio García Mejía 316
¿Qué es lo que hace JDBC?
•Establece una conexión con la base de datos.
•Envía estatutos SQL.•Procesa los resultados.
![Page 317: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/317.jpg)
José Antonio García Mejía 317
Estableciendo conexión
Connection con = DriverManager.getConnection(“jdbc:odbc:wombat”,”l
ogin”,”password”);
![Page 318: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/318.jpg)
José Antonio García Mejía 318
Enviando estatutos
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“Select *
fromTable”);
![Page 319: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/319.jpg)
José Antonio García Mejía 319
Procesando resultados
while (rs.next()){
int x = getInt(1);String s = getString(2);
}
![Page 320: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/320.jpg)
José Antonio García Mejía 320
JDBC vs. ODBC
•ODBC utiliza una interfaz C.
•ODBC es difícil de usar desde otros lenguajes.
•ODBC utiliza apuntadores void*
•ODBC es difícil de aprender.
•ODBC puede trabajar con JDBC.
![Page 321: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/321.jpg)
José Antonio García Mejía 321
Modelos de 2 y 3 enlaces
JDBC soporta los modelos de 2 y 3
enlaces de base de datos.
![Page 322: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/322.jpg)
José Antonio García Mejía 322
Modelo de 2 enlaces
![Page 323: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/323.jpg)
José Antonio García Mejía 323
Modelo de 2 enlaces
La aplicación o el applet habla
directamente a la base de datos.
![Page 324: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/324.jpg)
José Antonio García Mejía 324
Modelo de 2 enlaces
Requiere un controlador JDBC que
pueda comunicarse directamente con la
base de datos.
![Page 325: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/325.jpg)
José Antonio García Mejía 325
Modelo de 2 enlaces
Los estatutos SQL son enviados a la base de datos y los resultados
son regresados al usuario.
![Page 326: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/326.jpg)
José Antonio García Mejía 326
Modelo de 3 enlaces
![Page 327: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/327.jpg)
José Antonio García Mejía 327
Modelo de 3 enlaces
Los comandos son enviados a un enlace
intermedio (middle-tier)
![Page 328: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/328.jpg)
José Antonio García Mejía 328
Modelo de 3 enlaces
El middle-tier envía los estatutos SQL a la base
de datos
![Page 329: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/329.jpg)
José Antonio García Mejía 329
Modelo de 3 enlaces
La base de datos procesa los estatutos
SQL y regresa los resultados al middle-
tier
![Page 330: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/330.jpg)
José Antonio García Mejía 330
Modelo de 3 enlaces
El middle-tier regresa los resultados al
usuario.
![Page 331: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/331.jpg)
José Antonio García Mejía 331
JavaSoft FrameWork
El admnistrador de controladores JDBC.
El suite de prueba de controladores JDBC.
El bridge JDBC-ODBC
![Page 332: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/332.jpg)
José Antonio García Mejía 332
JavaSoft FrameWork
![Page 333: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/333.jpg)
José Antonio García Mejía 333
ABRIENDO UNA CONEXIÓN
String url=“jdbc:odbc:db”;Connection con = DriverManager.getConnection(url,”login”,”password”);
![Page 334: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/334.jpg)
José Antonio García Mejía 334
JDBC URLs
Provee la forma de identificar una base de datos a fin de
que el controlador apropiado la reconozca y establezca
una conexión con la misma.
![Page 335: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/335.jpg)
José Antonio García Mejía 335
JDBC URLs
jdbc:<subprotocol>:<subname>
![Page 336: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/336.jpg)
José Antonio García Mejía 336
El subprotocoloODBC
jdbc:odbc:<data-source-name>[;<atribute-name>=<atribute-
name>]*
![Page 337: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/337.jpg)
José Antonio García Mejía 337
Ejemplos ODBC
jdbc:odbc:qeor7jdbc:odbc:wombatjdbc:odbc:wombat;CacheSize=20jdbc:odbc:qeora;UID=kgh;PWD=fooey
![Page 338: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/338.jpg)
José Antonio García Mejía 338
DriverManager
Es una capa administradora que
trabaja entre el usuario y los controladores
![Page 339: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/339.jpg)
José Antonio García Mejía 339
CARGANDO EL CONTROLADOR
Class.forName(“acme.db.Driver”);
![Page 340: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/340.jpg)
José Antonio García Mejía 340
CARGANDO EL CONTROLADOR
•Se crea una instancia de la clase Driver.
•Se invoca al método DriverManager.registerDriver
![Page 341: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/341.jpg)
José Antonio García Mejía 341
Estableciendo la conexión
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url=“jdbc:odbc:fred”;DriverManager.getConnection(url,”login”,”passwd”);
![Page 342: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/342.jpg)
José Antonio García Mejía 342
INTRODUCCIÓN A LA TECNOLOGÍA OOP
JAVA
SESIÓN -15
![Page 343: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/343.jpg)
José Antonio García Mejía 343
OBJETIVO
Conocer como enviar estatutos SQL a una base de datos desde
JDBC
![Page 344: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/344.jpg)
José Antonio García Mejía 344
LA CLASE Statement
Un objeto Statement se utiliza para enviar estatutos SQL a una
base de datos
![Page 345: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/345.jpg)
José Antonio García Mejía 345
TIPOS DE OBJETOS Statement
•Statement
•PreparedStatement
•CallableStatement
![Page 346: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/346.jpg)
José Antonio García Mejía 346
OBJETOS Statement
Ejecuta estatutos SQL simples sin parámetros
![Page 347: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/347.jpg)
José Antonio García Mejía 347
OBJETOS PreparedStatement
Ejecuta estatutos SQL simples
precompilados con o sin parámetros IN
![Page 348: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/348.jpg)
José Antonio García Mejía 348
OBJETOS CallableStatement
Ejecuta una llamada a un procedimientos almacenado en la
base de datos
![Page 349: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/349.jpg)
José Antonio García Mejía 349
CREANDO OBJETOS Statement
Connection con=DriverManager.getConnection(url,
”sunny”,””);
Statement stmt = con.createStatement();
![Page 350: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/350.jpg)
José Antonio García Mejía 350
ENVIANDO ESTATUTOS SQL
ResultSet rs=stmt.executeQuery(“Select a,b,c from Table”);
![Page 351: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/351.jpg)
José Antonio García Mejía 351
MÉTODOS PARA EJECUTAR ESTATUTOS UTILIZANDO
OBJETOS Statement
•executeQuery
•executeUpdate
•execute
![Page 352: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/352.jpg)
José Antonio García Mejía 352
MÉTODO executeQuery
•Está diseñado para estatutos que producen un sólo conjunto resultado.
•Por ej., SELECT
![Page 353: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/353.jpg)
José Antonio García Mejía 353
MÉTODO executeUpdate
•Estatutos INSERT, UPDATE, DELETE.
•Estatutos de DDL : CREATE TABLE, DROP TABLE.
Se utiliza para ejecutar :
![Page 354: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/354.jpg)
José Antonio García Mejía 354
MÉTODO executeUpdate
Para estatutos como CREATE TABLE o DROP TABLE el valor
regresado es siempre 0
![Page 355: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/355.jpg)
José Antonio García Mejía 355
EJECUCIÓN CONSECUTIVA DE
MÉTODOS Statement
Todos los métodos para ejecutar estatutos Statement cierran el conjunto resultado actual, si existe uno abierto
![Page 356: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/356.jpg)
José Antonio García Mejía 356
LA CLASE ResultSet
Contiene todos los renglones que han
satisfecho las condiciones de un
estatuto SQL
![Page 357: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/357.jpg)
José Antonio García Mejía 357
LA CLASE ResultSet
Permite acceder a los datos en los
renglones del resultado
![Page 358: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/358.jpg)
José Antonio García Mejía 358
LA CLASE ResultSet
Permite acceder a los datos en los
renglones del resultado
![Page 359: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/359.jpg)
José Antonio García Mejía 359
EJEMPLO
Statement stmt=con.createStatement( );
ResultSet r = stmt.executeQuery(“Select a,b,c from Table1”);
![Page 360: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/360.jpg)
José Antonio García Mejía 360
EJEMPLO
while (r.next())
{
int i = r.getInt(“a”);
String s=r.getString(“b”);
float f=r.getFloat(“c”);
}
![Page 361: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/361.jpg)
José Antonio García Mejía 361
RENGLONES
•El OBJETO ResultSet mantiene un cursor al renglón de datos actual.
•Al inicio el cursor se coloca un renglón antes del primer renglón.
•El método next() avanza el cursor.
![Page 362: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/362.jpg)
José Antonio García Mejía 362
COLUMNAS
•Se accede a las columnas del renglón actual con los métodos getXXX.
•Puede utilizarse el número o el nombre de la columna.
![Page 363: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/363.jpg)
José Antonio García Mejía 363
EJEMPLO COLUMNAS
•String s = rs.getString(“titulo”);
•String s = rs.getString(2);
![Page 364: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/364.jpg)
José Antonio García Mejía 364
COLUMNAS
En el caso de QUERY’s “SELECT *” no es posible usar los nombres
de los campos
![Page 365: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/365.jpg)
José Antonio García Mejía 365
RESULTADOS NULL
•Utilice el método getXXX correspondiente.
•Utilice el método ResultSet.wasNull
![Page 366: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/366.jpg)
José Antonio García Mejía 366
EL BRIDGE JDBC-ODBC
Es posible utilizar un controlador Java Puro
en lugar del controlador y bridge
JDBC-ODBC
![Page 367: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/367.jpg)
José Antonio García Mejía 367
JDBC PURO vs JDBC-ODBC
Esto elimina la configuración
necesaria en el cliente requerida por ODBC
![Page 368: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/368.jpg)
José Antonio García Mejía 368
JDBC PURO vs JDBC-ODBC
Elimina el error potencial de que la
JVM se corrompa por errores en el código
nativo del Bridge
![Page 369: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/369.jpg)
José Antonio García Mejía 369
¿QUÉ ES EL BRIDGE JDBC-ODBC?
Es un controlador JDBC que implementa las operaciones JDBC
traduciéndolas en operaciones ODBC
![Page 370: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/370.jpg)
José Antonio García Mejía 370
¿QUÉ ES EL BRIDGE JDBC-ODBC?
Para ODBC se muestra como un
programa de aplicación normal.
![Page 371: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/371.jpg)
José Antonio García Mejía 371
¿QUÉ ES EL BRIDGE JDBC-ODBC?
El Bridge implementa JDBC para cualquier base de datos para la
cual exista un controlador ODBC
![Page 372: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/372.jpg)
José Antonio García Mejía 372
¿QUÉ ES EL BRIDGE JDBC-ODBC?
Es implementado en el paquete
sun.jdbc.odbc
![Page 373: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/373.jpg)
José Antonio García Mejía 373
VERSIÓN DE ODBC SOPORTADA
ODBC 2.x
![Page 374: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/374.jpg)
José Antonio García Mejía 374
USANDO EL BRIDGE
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
![Page 375: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/375.jpg)
José Antonio García Mejía 375
DRIVERS ODBC QUE FUNCIONAN CON EL BRIDGE
Oracle, Sybase, Informix, Microsoft SQL Server, Ingres,
xBASE, Access
![Page 376: Introducción POO](https://reader033.vdocuments.pub/reader033/viewer/2022050920/54f5d5ce4a7959d76e8b50e2/html5/thumbnails/376.jpg)
José Antonio García Mejía 376
DEBUGGING
java.sql.DriverManager.setLogStream(System.out);