You are on page 1of 126

CURSO DE JAVA

Variables (Datos envoltorio):

public class holaMundo {

public static void main(String[] args) {

Byte mordida;
mordida=(byte)126.55;
System.out.println("mordida="+mordida);

Short corto;
corto=(short)32000.55;
System.out.println("corto="+corto);

Integer entero;
entero=32000;
System.out.println("entero="+entero);

Long largo;
largo=(long)32000;
System.out.println("largo="+largo);

Float flotante;
flotante=mordida.floatValue();
System.out.println("flotante="+flotante);

Double doble;
doble=32000.55;
System.out.println("doble="+doble);

char caracter;
caracter='c';
System.out.println("caracter="+caracter);

Boolean boleano;
boleano=false;
System.out.println("boleano="+boleano);

String cadena;
cadena="cadena";
System.out.println("cadena="+cadena);
}
}

Constantes:

package com.programadornovato.proy1;

public class holaMundo {

public static void main(String[] args) {

Byte mordida;
mordida=(byte)126.55;
System.out.println("mordida="+mordida);

Short corto;
corto=(short)32000.55;
System.out.println("corto="+corto);

Integer entero;
entero=32000;
System.out.println("entero="+entero);

Long largo;
largo=(long)32000;
System.out.println("largo="+largo);

Float flotante;
flotante=mordida.floatValue();
System.out.println("flotante="+flotante);

Double doble;
doble=32000.55;
System.out.println("doble="+doble);
char caracter;
caracter='c';
System.out.println("caracter="+caracter);

Boolean boleano;
boleano=false;
System.out.println("boleano="+boleano);

String cadena;
cadena="cadena";
System.out.println("cadena="+cadena);
}
}

Ingresar datos por consola(Scanner):

package com.programadornovato.proy1;
import java.util.Scanner;

public class holaMundo {

public static void main(String[] args) {

Scanner inInt=new Scanner (System.in);


int entero;
System.out.println("Escriba un numero entero");
entero=inInt.nextInt();
System.out.println("Su numero es: "+entero);

Scanner inFloat=new Scanner (System.in);


float flotante;
System.out.println("Escriba un numero flotante");
flotante=inFloat.nextFloat();
System.out.println("Su numero es: "+flotante);

Scanner inCadena=new Scanner (System.in);


String cadena;
System.out.println("Escriba una cadena");
cadena=inCadena.nextLine();
System.out.println("Su cadena es: "+cadena);

Scanner inCaracter=new Scanner (System.in);


char caracter;
System.out.println("Escriba un caracter");
caracter=inCaracter.next().charAt(0);
System.out.println("Su caracter es: "+caracter);
}
}

Ingresar datos via showInputDialog:


package com.programadornovato.proy1;

import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {

char caracter= JOptionPane.showInputDialog("Mete un


caracter").charAt(0);
JOptionPane.showMessageDialog(null,"Este es tu caracter
" + caracter);

String cadena= JOptionPane.showInputDialog("Mete un


nombre");
JOptionPane.showMessageDialog(null,"Esta es una
cadena de texto" + cadena);

int entero =
Integer.parseInt(JOptionPane.showInputDialog("Introduce
un numero entero: "));
JOptionPane.showMessageDialog(null, "Este es tu numero
entero: " + entero);
}
}
Operadores matemáticos:

package com.programadornovato.proy1;

import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {

Scanner entra=new Scanner(System.in);


float num1,num2,suma,resta,mul,div,residuo;
System.out.println("Inresa 2 numeros:");
num1=entra.nextFloat();
num2=entra.nextFloat();
suma=num1+num2;
resta=num1-num2;
mul=num1*num2;
div=num1/num2;
residuo=num1%num2;
System.out.println("Suma="+suma);
System.out.println("Resta="+resta);
System.out.println("Multiplicacion="+mul);
System.out.println("Divicion="+div);
System.out.println("Residuo="+residuo);
}
}

Operadores matemáticos cortos

package com.programadornovato.proy1;

import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


float num=5;
//num=num+1;
//num+=5;
//num++;
//num-=4;
//num--;
//num*=5;
//num/=5;
num%=5;
System.out.println("Res="+num);
}
}

Operador incremental y decremental:


package com.programadornovato.proy1;

import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


int num1=5;
int num2=0;
num2=--num1;
System.out.println("num1="+num1);
System.out.println("num2="+num2);
}
}

Operaciones matemáticas con Math:

package com.programadornovato.proy1;

import java.util.Scanner;
import javax.swing.JOptionPane;
public class holaMundo {
public static void main(String[] args) {

double numRaiz=8;
double resRaiz=0;
resRaiz=Math.sqrt(numRaiz);
System.out.println("resRaiz=" + resRaiz);

double base=5;
double exp=2;
double resExpo;

resExpo=Math.pow(base, exp);
System.out.println("resExpo= " + resExpo);

//CAMBIA UN NUMERO NEGATIVO EN UNO POSITIVO


float numAbsoluto = -5.5f;
double resAbsoluto=Math.abs(numAbsoluto);
System.out.println("resAbsoluto= " + resAbsoluto);

//REDONDEAR UN NUMERO
float numRed=5.5f;
int resRed=Math.round(numRed);
System.out.println("resRed=" + resRed);

double resAle=Math.random();
System.out.println("resAle= " + Math.round(resAle*100));
}
}

Sumar 3 productos y redondear la venta y además sacar el


redondeo que queda de residuo en dinero:
package com.programadornovato.proy1;

import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {

Scanner entrada = new Scanner(System.in);

System.out.println("Ingrese el valor del producto 1: ");


//TOMAMOS EL VALOR DEL PRODUCTO 1
float producto_1 = entrada.nextFloat();
System.out.println("Ingrese el valor del producto 2: ");

//TOMAMOS EL VALOR DEL PRODUCTO 2


float producto_2 = entrada.nextFloat();
System.out.println("Ingrese el valor del producto 3: ");

//TOMAMOS EL VALOR DEL PRODUCTO 3


float producto_3 = entrada.nextFloat();

float suma = producto_1 + producto_2 + producto_3;


System.out.println("La suma de sus productos es: " +
suma);

double totalMasRedondeo = Math.ceil(suma);


//float totalMasaRedondeo = Math.round(suma);
System.out.println("El total pagado es: " +
totalMasRedondeo);

double res_redondeo = totalMasRedondeo - suma;


System.out.println("Este es el valor del redondeo: " +
res_redondeo);
}
}

Ejercicio:
Si yo me emborracho con 2 litros de cerveza y un baso mide 6cm de
diámetro y 10cm de altura. ¿Cuántos vasos debo tomar para
emborracharme? Sabiendo que la formula del volumen de un cilindro
2 d
es V =π h r= 2
package com.programadornovato.proy1;

import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {
Scanner entra=new Scanner(System.in);
System.out.print("Diametro del vaso=");
float diametro=entra.nextFloat();
System.out.print("Altura del vaso=");
float altura=entra.nextFloat();
double volumen;
float pi=3.1416f;
float radio=diametro/2;
volumen=pi*Math.pow(radio, 2)*altura;
System.out.println("Vol de un vaso de cerveza
es:"+volumen);
System.out.print("Con cuantos litros te emborrachas?");
float litros=entra.nextFloat();
float mililitrosParaEmborracharme=litros*1000;
double limiteVasos=mililitrosParaEmborracharme/volumen;
System.out.println("Yo me emborracho
con :"+limiteVasos+" vasos de cerveza");
}
}

Ejercicio 3: Calcular edad de una persona,


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


Calendar fechaNac=new GregorianCalendar(1975,10,27);
Calendar fechaHoy=Calendar.getInstance();
int anoNac=fechaNac.get(Calendar.YEAR);
int anoHoy=fechaHoy.get(Calendar.YEAR);
int edad=anoHoy-anoNac;
System.out.println("Edad="+edad);
}
}

Condicionales (Sentencia if else)


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


Scanner entra=new Scanner(System.in);
int numUser,numSis;
numSis=(int)(Math.random()*10);
System.out.print("Ingresa un numero mayor o igual a
"+numSis+": ");
numUser=entra.nextInt();
if(numUser >= numSis){
System.out.println("Muy bien");
}
else{
System.out.println("Muy mal");
}
}
}
Condicionales(switch case):

package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


Scanner entra=new Scanner(System.in);
System.out.println("Seleccione una opcion\n1: Acceso\n2:
Configuracion\n3: Ayuda");
int seleleccion=entra.nextInt();
switch(seleleccion){
case 1:
System.out.println("Seleccionaste el accesos");
break;
case 2:
System.out.println("Seleccionaste la configuracion");
break;
case 3:
System.out.println("Seleccionaste la ayuda");
break;
default:
System.out.println("Opcion no valida");
break;
}
}
}
Condicionales con String
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


Scanner entra=new Scanner(System.in);
/*
System.out.println("Escribe una opcion\nacceso\
nconfiguracion\nayuda");
String seleleccion=entra.nextLine();
seleleccion=seleleccion.toLowerCase();
switch(seleleccion){
case "acceso":
System.out.println("Seleccionaste el acceso");
break;
case "configuracion":
System.out.println("Seleccionaste la configuracion");
break;
case "ayuda":
System.out.println("Seleccionaste la ayuda");
break;
default:
System.out.println("Opcion no valida");
break;
}
*/
System.out.println("Saludame por favor");
String respuesta= entra.nextLine();
respuesta=respuesta.toLowerCase();
if(respuesta.equals("hola") ==true){
System.out.println("¿Como estas?");
}
else{
System.out.println("No te entiendo");
}
}
}

Ejercicio 1: condicionales anidadas


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


Scanner entra=new Scanner(System.in);
System.out.println("Escribe un numero entre 1 y 999");
int num=entra.nextInt();
if(num>0 && num <10){
System.out.println("Tu numero es unidad");
}
else{
if(num >=10 && num <100){
System.out.println("Tu numero es decena");
}
else{
if(num >=100 && num<1000){
System.out.println("Tu numero es centena");
}
}
}
}
}
Ejercicio 2: Juego de azar
Juego de dados:
1. Si los tres dados son 6, muestra “Excelente”
2. Si dos dados salen 6, muestra “Muy bien”,
3. Si un dado sale 6, muestra “Regular”,
4. Si ningún dado sale 6, muestra “Pésimo”.
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {
Random rand=new Random();
int d1=rand.nextInt(6)+1;
int d2=rand.nextInt(6)+1;
int d3=rand.nextInt(6)+1;
System.out.println("Dado 1="+d1);
System.out.println("Dado 2="+d2);
System.out.println("Dado 3="+d3);
if(d1==6 && d2==6 && d3==6){
System.out.println("Excelente");
}
else{
if( (d1==6 && d2==6) || (d1==6 && d3==6) || (d2==6
&& d3==6) ){
System.out.println("Muy bien");
}
else{
if(d1==6 || d2==6 || d3==6){
System.out.println("Regular");
}
else{
if(d1!=6 && d2!=6 && d3!=6){
System.out.println("Pesimo");
}
}
}
}
}
}

Ciclo con While:


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {
/*
int i=1;
while(i<=10){
System.out.println("i="+i);
i=i+1;
}
int i=10;
while(i>=1){
System.out.println("i="+i);
i=i-1;
}
*/
Scanner entra=new Scanner(System.in);
System.out.println("Humano cuantas veces quieres que se
repita");
int repeticiones= entra.nextInt();
int i=1;
while(i<=repeticiones){
System.out.println("i="+i);
//i++
i=i+2;
}
}
}

Ciclo con do While:


package com.misproyectos.proy_1;

import java.util.Random;

public class Proy_1 {

public static void main(String[] args) {


/*int i = 1;
do{
System.out.println("i= " + i );
i++;
}while(i <= 10);
int j = 10;
do{
System.out.println("j= " + j );
j--;
}while(i >= 1);
*/
Random rand = new Random();
int aleatorio = rand.nextInt(5) + 1;
System.out.println("Aleatorio= " + aleatorio);
int i = 1;
do{
System.out.println("i= " + i);
i++;
}while(i <= aleatorio);
}
}
Ciclo con for:
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

class holaMundo {

public static void main(String[] args) {


/*
for(int i=1;i<=10;i++){
System.out.println("i="+i);
}
for(int i=10;i>=1;i--){
System.out.println("i="+i);
}
*/
Scanner entra=new Scanner(System.in);
System.out.println("Humano cuantas repeticiones quieres");
int repeticiones = entra.nextInt();
for(int i=1; i< = repeticiones; i++){
System.out.println("i= " + i);
}
}
}

Ejercicio 1: Dibujar una escalera con asteriscos con ciclo for:

package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {
String texto=JOptionPane.showInputDialog("Humano dame
la altura de tu pinche escalera");
int altura = Integer.parseInt(texto);
for(int numAsterisco = 1; numAsterisco <= altura;
numAsterisco++){
for(int i=0; i<numAsterisco; i++){
System.out.print("*");
}
System.out.println("");
}
}
}

Ejercicio 2: Adivinar un numero random en Java.


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {
Random rand = new Random();
int aleatorio = rand.nextInt(5) + 1;
int num =
Integer.parseInt(JOptionPane.showInputDialog("Humano
que numero estoy pensado (entre 1 y 5) dijita 0 para
salir"));
while (num != aleatorio){
num =
Integer.parseInt(JOptionPane.showInputDialog("Humano te
equivocaste en que numero estoy pensado (entre 1 y 5)
dijita 0 para salir"));
if (num == 0){
break;
}
aleatorio = rand.nextInt(5)+1;
}
If (num != 0){
JOptionPane.showMessageDialog(null, "Bien jugado
humano");
}
else{
JOptionPane.showMessageDialog(null, "Huamno estupido
el numero era " + aleatorio);
}
}
}

Ejercicio 3: obtener promedio con do while


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {
int contador = 0;
float calificación = 0, suma = 0, promedio;
String texto;
do{
texto = JOptionPane.showInputDialog("Ingresa la
calificacion del semestre " + (contador + 1));
System.out.println(texto);
if(texto != null){
calificación = Float.parseFloat(texto);
suma = suma + calificacion;
contador++;
}
}while(texto != null);
if(contador > 0){
promedio = suma / contador;
JOptionPane.showMessageDialog(null, "Promedio=" +
promedio);
}
else{
JOptionPane.showMessageDialog(null, "Humano estupido
debes de poner por lo menos una calificacion");
}
}
}

 Arreglos: Un arreglo puede definirse como un grupo o una


colección finita, homogénea y ordenada de elementos

package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


//Un arreglo puede definirse como un grupo o una
colección finita, homogénea y ordenada de elementos
//0,1,2,3
int [ ] listaNumeros = {5, 3, 9, 1};
for(int i = 0; i <= 3; i++){
System.out.println(listaNumeros [ i ]);
}
}
}
Arreglos de caracteres:
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[ ] args) {


String texto = JOptionPane.showInputDialog("Humano!!!! escribe
un texto");
int longitud = texto.length();
char[ ] caracteres = new char[longitud];
int inverso = longitud;
for(int i = 0; i < longitud; i++){
caracteres[ i ] = texto.charAt(inverso - 1);
inverso--;
}
System.out.println(caracteres);
}
}

foreach en java:
package com.programadornovato.proy1;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {
String [ ] perros =
{"Monte","Chupacabras","Solovino","Chimuelo","La
wera","El chiquito"};

//FOR NORMAL
for(int i = 0; i < perros.length; i++){
System.out.println((i + 1)+" "+perros[ i ]);
}
System.out.println("_________________");
int i = 1;
//ACA CREAMOS EL FOR EACH
for(String perro:perros){
System.out.println(i + " " + perro);
i++;
}
}
}

Ejercicio 1: identificar un palíndromo, son palabras que se leen al


derecho y son igual si se leen al revés.

package com.misproyectos.proy_1;

import javax.swing.JOptionPane;

public class Proy_1 {

public static void main(String[] args) {


String texto = JOptionPane.showInputDialog("Escribe un
palindromo");
int longitud = texto.length();
char [] letras = new char[longitud];
char [] letrasInversas = new char[longitud];
int inverso = longitud;
boolean igual = true;
for(int i = 0; i < longitud; i++){
letrasInversas[i] = texto.toLowerCase().charAt(inverso-1);
inverso--;
letras[i] = texto.toLowerCase().charAt(i);
if(letrasInversas[i] != letras[i]){
igual = false;
break;
}
}
if(igual == false){
System.out.println("Esto no es un palindromo");
}else{
System.out.println("Bien jugado" + texto + "si es un
palindromo");
}
}
}
Ejercicio 2: con números:
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {


public static void main(String[] args) {
//5,4,2,1,3
String texto = JOptionPane.showInputDialog("Humano
ingresa numero divididos por coma");
String numerosEnTexto[ ] = texto.split(",");
int cantidad = numerosEnTexto.length;
int numeros[ ] = new int[cantidad],tem;
for(int i = 0; i < cantidad; i++){
numeros[ i ] = Integer.parseInt( numerosEnTexto[ i ]);
}
for(int i = 0; i < (cantidad - 1); i++){
for(int j = 0; j < (cantidad - 1); j++){
if(números [ j ] > números [ j + 1]){
tem = numeros[ j ];
numeros[ j ] = números [ j + 1];
numeros[ j + 1] = tem;
}
}
}
System.out.println("Humano aqui estan tus numeritos
ordenados de forma acendente");
for(int i = 0; i < cantidad; i++){
System.out.print(numeros[ i ] + ",");
}
System.out.println("\nHumano aqui estan tus numeritos
ordenados de forma decendente");
for(int i = cantidad - 1; i >= 0; i--){
System.out.print(numeros[ i ] + ",");
}
}
}

Ejercicio 3: Calcular promedio de un alumno


package com.programadornovato.proy1;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[ ] args) {


String texto;
float calificaciones[ ] = new float[4], suma = 0, promedio =
0;
int semestres = 0;
do{
texto=JOptionPane.showInputDialog("Humano!! ingresa la
calificacion del alumno del semestre "+(semestres+1));
if (texto == null){
break;
}
Calificaciones [semestres] = Float.parseFloat (texto);
semestres++;
}while (semestres < 4);
for (float calificacion:calificaciones){
suma += calificacion;
}
Promedio = suma / semestres;
JOptionPane.showMessageDialog(null, promedio);
}
}

Ejercicio 4: Mezclar 2 arreglos


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


int a [ ] = new int [5], b [ ] = new int[5],c [ ] = new int[10];
for(int i = 0; i < 5; i++){
a[i]=
Integer.parseInt(JOptionPane.showInputDialog("Humano
ingresa el valor " + ( i + 1 ) + " del arreglo a"));
}
for (int i = 0; i < 5; i++){
b[i]=
Integer.parseInt(JOptionPane.showInputDialog("Humano
ingresa el valor " + (i + 1) + " del arreglo b"));
}
int j = 0;
for (int i = 0; i < 5; i++){
c [ j ] = a [ i ];
j++;
c [ j ] = b [ i ];
j++;
}
for(int elemento:c){
System.out.println(elemento);
}
}
}

Ejercicio 5: Obtener el número mayor de un arreglo


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


String texto = JOptionPane.showInputDialog("Humano
ingresa numero divididos por coma");
//5,6,7,10,5
String numerosEnTexto [ ] = texto.split(",");
int cantidad = numerosEnTexto.length;
int números [ ] = new int[cantidad];
for(int i = 0; i < cantidad; i++){
números [ i ] = Integer.parseInt( numerosEnTexto [ i ]);
}
int mayor = 0;
for (int numero:numeros){
if (numero > mayor){
mayor = numero;
}
}
JOptionPane.showMessageDialog(null, "Humano este es tu
numero mayor= " + mayor);
}
}

Ordenamiento de tipo burbuja:


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String [ ] args) {


//5,4,2,1,3
String texto = JOptionPane.showInputDialog("Humano
ingresa numero divididos por coma");
String numerosEnTexto [ ] = texto.split(",");
int cantidad = numerosEnTexto.length;
int números [ ] = new int[cantidad],tem;
for (int i = 0; i < cantidad; i++){
números [ i ] = Integer.parseInt( numerosEnTexto [ i ]);
}
for (int i = 0; i < (cantidad - 1); i++){
for (int j = 0; j < (cantidad - 1); j++){
if (números [ j ] > números [ j + 1]){
tem = números [ j ];
números [ j ] = números [ j + 1];
números [ j + 1] = tem;
}
}
}
System.out.println("Humano aqui estan tus numeritos
ordenados de forma acendente");
for (int i = 0; i < cantidad; i++){
System.out.print(números [ i ] + ",");
}
System.out.println("\nHumano aqui estan tus numeritos
ordenados de forma decendente");
for (int i = cantidad - 1; i >= 0; i--){
System.out.print(números [ i ] + ",");
}
}
}

Burbuja mejorado:
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String [ ] args) {


//5,4,2,1,3
String texto = JOptionPane.showInputDialog("Humano
ingresa numero divididos por coma");
String numerosEnTexto [ ] = texto.split(",");
int cantidad = numerosEnTexto.length;
int números [ ] = new int[cantidad],tem,bandera = 1, ciclos
= 0;
for (int i = 0; i < cantidad; i++){
números [ i ] = Integer.parseInt( numerosEnTexto [ i ]);
}
for(int i = 0; i < (cantidad - 1) && bandera == 1; i++){
bandera = 0;
for (int j = 0; j < (cantidad - 1); j++) {
if (números [ j ] > números [ j + 1]){
bandera = 1;
tem = números [ j ];
números [ j ] = numeros[ j + 1];
números [ j + 1] = tem;
}
}
ciclos++;
}
System.out.println("Humano aqui estan tus numeritos
ordenados de forma acendente y me tomo " + ciclos + "
ciclos");
for (int i = 0; i < cantidad; i++){
System.out.print(números [ i ] + ",");
}
System.out.println("\nHumano aqui estan tus numeritos
ordenados de forma decendente y me tomo " + ciclos + "
ciclos");
for (int i = cantidad – 1; i >= 0; i--){
System.out.print(números [ i ] + ",");
}
}
}
Ordenamiento por selección:
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


//5 4 2 1 3
Scanner entra = new Scanner(System.in);
int elemento [ ] = new int [ 5 ], menor, posicion, temporal;
System.out.println("Humano holgaza escribe 5 numero
para que yo los ordene");
for (int i = 0; i < 5; i++){
elemento [ i ] = entra.nextInt();
}
for (int i = 0; i < elemento.length - 1; i++){
menor = elemento [ i ];
posicion = i;
for (int j = i + 1; j < elemento.length; j++){
if (elemento [ j ] < menor){
menor = elemento [ j ];
posicion = j;
}
}
If (posicion != i){
temporal = elemento [ i ];
elemento [ i ] = elemento [ posicion ];
elemento [ posicion ] = tem;
}
}
System.out.println("Humano aqui estan tus elementos
ordenados de forma acendente");
for (int i = 0; i < elemento.length; i++){
System.out.print(elemento [ i ] + ",");
}
System.out.println("Humano aqui estan tus elementos
ordenados de forma decendente");
for (int i = elemento.length - 1; i >= 0; i--){
System.out.print(elemento [ i ] + ",");
}
}
}

 Busqueda secuencial:
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


//5 10 15 58 20 56 65
Scanner entra = new Scanner(System.in);
int elemento [ ] = new int [ 7 ];
System.out.println("Humano escribe 7 numeros");
for (int i = 0; i < 7; i++){
elemento [ i ] = entra.nextInt();
}
System.out.println("Humano ahora ingresa tu numero a
buscar");
int numBuscar = entra.nextInt();
int i = 0;
boolean bandera = false;
while ( i < 7 && bandera == false){
if ( numBuscar == elemento [ i ]){
bandera = true;
}
i++;
}
If ( bandera ){
System.out.println("Humano!!! ya encontre tu numero en la
posicion " + i);
}
else{
System.out.println("Humano no encontre tu numerito");
}
}
}

Busqueda binaria:
package com.programadornovato.proy1;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


//5 10 15 30 50 70 90 95
Scanner entra = new Scanner(System.in);
int elemento [ ] = new int [ 8 ];
System.out.println("Humano holgazan escribe 8 numeros");
for (int i = 0; i < 8; i++){
elemento [ i ]= entra.nextInt();
}
System.out.println("Humano ahora ingresa tu piche numero
a buscar");
int numBuscar = entra.nextInt();
int n = elemento.length, inf = 0, centro = 0;
int sup = n - 1;
boolean bandera=false;
while (inf <= sup){
centro = (sup + inf) / 2;
if (elemento [centro] == numBuscar){
bandera = true;
break;
}
else if (numBuscar < elemento[centro]){
sup = centro -1;
}
else{
inf = centro + 1;
}
}
If (bandera == true){
System.out.println("Humano ya encontre tu numero estaba
en la pos " + (centro + 1));
}
else{
System.out.println("Lo siento Humano no encontre tu
numerito");
}
}
}

Que es una matriz (matrix):


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String [ ] args) {


//5 20 30
//8 15 5
//54 5 2
//int matriz[ ] [ ]={{5,20,30},{8,15,5},{54,5,2}};
Scanner entra=new Scanner(System.in);
System.out.println("Humano cuantas filas tene tu matriz:");
int reg = entra.nextInt();
System.out.println("Humano cuantas columnas tene tu
matriz:");
int col = entra.nextInt();
int matriz [ ][ ]=new int[ reg ][ col ];
for (int i = 0; i < 3; i++){
System.out.println("Humano ingresa 3 datos de la fila
" + ( i +1));
for (int j = 0; j < 3; j++){
matriz [ i ] [ j ] = entra.nextInt();
}
}
System.out.println("\nHumano esta es tu matriz");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
System.out.print(matriz [ i ] [ j ] + ",");
}
System.out.println(" ");
}
}
}

Matriz de String:
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[ ] args) {


/*
Maria Ramirez C
Juan Perez B
Ines Montes B
Rene Pacheco B
Elena Morales A
Mario Dias C
Sonia Navarro A
*/
String alumnos[ ][ ]=new String[7][3];
Scanner entra = new Scanner(System.in);
for(int i = 0; i < alumnos.length; i++){
System.out.println("Humano!!! ingresa los datos del alumno
" + ( i +1));
for (int j = 0; j < 3; j++){
alumnos[ i ][ j ] = entra.next();
}
}
System.out.println("Humano!!! ¿Dime de que aula quieres
ver tus alumnos?");
String aula = entra.next();
aula = aula.toLowerCase();
for (int i = 0; i < alumnos.length; i++){
if(alumnos[ i ][ 2 ].toLowerCase().equals(aula)){
System.out.println("");
for (int j = 0; j < 3; j++){
System.out.print(alumnos[ i ] [ j ] + " ");
}
}
}
}
}

Matriz traspuesta: Convertir las filas en columnas


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


/*
123
456
789
*/
int matriz[ ][ ] = new int[3][3];
int matrizT[ ][ ]=new int[3][3];
Scanner entra = new Scanner(System.in);
for (int i = 0; i < 3; i++){
System.out.println("Humano!!! ingresa los datos de la
fila " + (i+1));
for (int j = 0; j < 3; j++){
matriz [ i ] [ j ] = entra.nextInt();
}
}
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
matrizT [ j ] [ i ] = matriz [ i ] [ j ];
}
}
System.out.println("Humano aqui esta tu matriz
traspuesta");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
System.out.print(matrizT [ i ] [ j ] + "\t");
}
System.out.println("");
}
}
}

Demostrar que una matriz es simétrica:


Que tiene que ser exactamente igual ósea 3x3 o 4x4 etc., en las filas y
columnas tienen que estar los números exactos.
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[ ] args) {


Scanner entra=new Scanner(System.in);
System.out.println("Humano dime cuantas filas tiene tu
matriz");
int fil = entra.nextInt();
System.out.println("Humano dime cuantas columnas tiene
tu matriz");
int col = entra.nextInt();
int matriz[ ] [ ]=new int[ fil ] [ col ];
boolean esSimetrica = true;
for (int i = 0; i < fil; i++){
System.out.println("Humano ingresa los datos de la fila " + (
i +1));
for (int j = 0; j < col; j++){
matriz [ i ] [ j ] = entra.nextInt();
}
}
if (col == fil){
for (int i = 0; i < fil; i++){
for (int j = 0; j < col; j++){
if (matriz [ i ] [ j ] != matriz [ j ] [ i ]){
esSimetrica = false;
break;
}
}
if (esSimetrica == false){
break;
}
}
}
else{
System.out.println("Humano tu matriz para empesar no es
simetrica");
}
if (esSimetrica == true){
System.out.println("Humano felicidades tu matriz si es
simetrica");
}
else{
System.out.println("Nop no es simetrica");
}
}
}

Suma de filas y columnas de matrices:


package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[ ] args) {


Scanner entra=new Scanner(System.in);
System.out.println("Humano!! cuantas filas va a tener tu
inche matriz");
int fil = entra.nextInt();
System.out.println("Humano!! cuantas columnas va a tener
tu inche matriz");
int col=entra.nextInt();
int matriz [ ] [ ] = new int [ fil ] [ col ];
for (int i = 0; i < fil; i++){
System.out.println("Humano ingresa los datos de la
fila " + (i+1));
for (int j = 0; j < col; j++){
matriz [ i ] [ j ] = entra.nextInt();
}
}
int sumaFil=0;
for (int i = 0; i < fil; i++){
sumaFil = 0;
for (int j = 0; j < col; j++){
sumaFil = sumaFil + matriz [ i ] [ j ];
}
System.out.println("Humano esta es la suma de tu fila " + (
i+1) + " = " + sumaFil);
}
int sumaCol = 0;
for (int j = 0; j < col; j++){
sumaCol = 0;
for (int i = 0; i < fil; i++){
sumaCol = sumaCol + matriz [ i ] [ j ];
}
System.out.println("Humano esta es la suma de tu columna
" + ( j+1) + " = " + sumaCol);
}
}
}

Suma de una Diagonal de nuestra


Matriz:
package com.programadornovato.proy1;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String [ ] args) {


int matriz [ ] [ ] = new int [ 5 ] [ 5 ];
int dato = 1;
for (int i = 0; i < matriz.length; i++){
for (int j = 0; j < matriz [ i ].length; j++){
matriz [ i ] [ j ] = dato;
dato++;
}
}
for (int i = 0; i < matriz.length; i++){
for (int j = 0; j < matriz [ i ].length; j++){
System.out.print("\t" + matriz [ i ] [ j ]);
}
System.out.println(" ");
}
int diagonalPrincipal [ ] = new int [matriz.length];
int diagonalSecundaria [ ] = new int [matriz.length];
for (int i = 0; i < matriz.length; i++){
for (int j = 0; j < matriz [ i ].length; j++){
if (i == j){
diagonalPrincipal [ i ] = matriz [ i ] [ j ];
}
if ( ( i + j) == matriz.length -1){
diagonalSecundaria [ i ] = matriz [ i ] [ j ];
}
}
}
int suma = 0;
System.out.println("\nHumano este es tu diagonal principal");
for (int elemento:diagonalPrincipal){
System.out.print("\t" + elemento);
suma = suma + elemento;
}
System.out.print (" = " + suma);
System.out.println (" ");
suma = 0;
System.out.println("\nHumano este es tu diagonal
secundaria");
for (int elemento:diagonalSecundaria){
System.out.print("\t" + elemento);
suma = suma + elemento;
}
System.out.print(" = " + suma);
System.out.println(" ");
}
}

(Programación Orientada a Objetos) Mi


clase vehículo:
CREAMOS UN JAVA CLASS:
package com.misproyectos.proy_1;

public class Proy_1 {


public static void main(String[] args){
auto carro = new auto();
carro.modelo = "carro";
carro.color = "Rojo";
carro.marca = "Chevrolet";

carro.enciende();
carro.acelera();
carro.frenar();
System.out.println("Marca " + carro.marca);
}
}

CREAMOS UNA JAVA MAIN CLASS:


package com.programadornovato.proy1;

public class auto {


String marca;
String modelo;
String color;
public void enciende(){
System.out.println("Enciende run run");
}
public void acelera(){
System.out.println("Velocimetro 80km");
}
publicó void frenar(){
System.out.println("Velocimetro 0km");
}
}

POO Clases publicas y privadas:


CREAMOS UNA JAVA CLASS:
package com.programadornovato.proy1;

public class auto {

String marca;
String modelo;
String color;

private boolean acceso=false;


public void meterLlave(String clave){
if(clave.equals("123456")){
acceso=true;
}
else{
acceso=false;
System.out.println("Llamar a la policia");
}
}
public void mando(String accion){
if(acceso==true){
if(accion.equals("enciende")){
enciende();
}
}
}
private void enciende(){
System.out.println("Enciende run run");
}
public void acelera(){
System.out.println("Velocimetro 80km");
}
public void frenar(){
System.out.println("Velocimetro 0km");
}
}

DENTRO DE JAVA MAIN CLASS:


package com.misproyectos.proy_1;

public class Proy_1 {


public static void main(String[] args){
auto carro = new auto();
carro.modelo = "carro";
carro.color = "Rojo";
carro.marca = "Chevrolet";

carro.meterLlave("123456");
carro.mando("enciende");
carro.acelera();
carro.frenar();
System.out.println("Marca " + carro.marca);
}
}
POO método con retorno (Calculadora):
Acá en lugar de VOID le vamos a llamar INT

CLASE CALCULADORA:
package com.programadornovato.proy1;

public class Calculadora {


public int suma(int a,int b){
int res=0;
if(a>0 && b>0){
res=a+b;
}
return res;
}
public int resta(int a,int b){
int res=0;
if(a>0 && b>0){
res=a-b;
}
return res;
}
public int multiplicacion(int a,int b){
int res=0;
if(a>0 && b>0){
res=a*b;
}
return res;
}
public int divicion(int a,int b){
int res=0;
if(a>0 && b>0){
res=a/b;
}
retornó res;
}
}

CLASE MAIN PRINSIPAL DONDE MANDAMOS A LLAMAR LA


CALCULADORA:
package com.misproyectos.proy_1;

import java.util.Scanner;

public class Proy_1 {


public static void main(String[] args){
Calculadora cal = new Calculadora();
Scanner entra = new Scanner(System.in);
System.out.println("Humano ingresa dos numeros para sumar");
int resultado = cal.suma(entra.nextInt(), entra.nextInt());
System.out.println("Humano este es el resultado: " + resultado);

System.out.println("Humano ingresa dos numeros para restar");


resultado = cal.resta(entra.nextInt(), entra.nextInt());
System.out.println("Humano este es el resultado: " + resultado);

System.out.println("Humano ingresa dos numeros para


multiplicar");
resultado = cal.multiplicacion(entra.nextInt(), entra.nextInt());
System.out.println("Humano este es el resultado: " + resultado);

System.out.println("Humano ingresa dos numeros para dividir");


resultado = cal.divicion(entra.nextInt(), entra.nextInt());
System.out.println("Humano este es el resultado: " + resultado);
}
}

POO Método Constructor:


CLASE MAIN:
package com.misproyectos.proy_1;

import java.util.Scanner;

public class Proy_1 {


public static void main(String[] args){
Persona per = new Persona("Jaime ", 45);
System.out.println("Nombre: " + per.nombre + "Edad: " +
per.edad);
}
}

CLASE PERSONA:
package com.programadornovato.proy1;

public class Persona {


String nombre;
int edad;
public Persona(String _nombre,int _edad){
this.nombre=_nombre;
this.edad=_edad;
}
/*
public void inicializar(String _nombre,int _edad){
this.nombre=_nombre;
this.edad=_edad;
}
*/
}

POO Sobrecarga de métodos:


CLASE VEHICULO:
package com.programadornovato.proy1;

public class Vehiculo {


String marca;
String modelo;
String sku;

//ACA COMENZAMOS A CREAR LOS METODOS


CONSTRUCTORES
public Vehiculo(String marca, String modelo) {
this.marca = marca;
this.modelo = modelo;
}
public Vehiculo(String sku) {
this.sku = sku;
}
public void acelerar(){
if(this.marca != null && this.modelo != null ){
System.out.println("Tu poderoso "+ this.marca +" "+
this.modelo +" esta acelerando");
}
else if(this.sku!=null){
System.out.println("Tu poderoso "+ this.sku +" esta
acelerando");
}
}
public void acelerar(int km){
if(this.marca != null && this.modelo != null ){
System.out.println("Tu poderoso "+ this.marca +" "+
this.modelo +" esta acelerando a "+km+" km/h");
}
else if(this.sku!=null){
System.out.println("Tu poderoso "+ this.sku +" esta
acelerando a "+km+" km/h");
}
}
}

CLASE MAIN:

package com.misproyectos.proy_1;

public class Proy_1 {


public static void main(String[] args){
//llamamos los metodos
Vehiculo v1 = new Vehiculo("Sport", "2011");
//llamamos la instancia
v1.acelerar();

Vehiculo v2 = new Vehiculo("Super Sport");


v2.acelerar(50);
}
}

Crear paquetes y clases principales:


Clase 1:
package Paquete1;

public class Clase1 {


public static void main(String arg[]){
System.out.println("Clase 1");
}
}
Clase 2:
package Paquete1;

public class Clase2 {

}
Clase 3:
package Paquete2;

public class Clase3 {


public static void main(String[] args) {
System.out.println("Clase 3");
}
}

Modificadores de acceso:
Clase 1:
package Paquete1;

public class Clase1 {


public static void main(String[] arg){
Clase2 c2 = new Clase2();
System.out.println(c2.atributo);
}
}

Clase 2:
package Paquete1;

public class Clase2 {


public int atributo = 10;
}

Clase 3:
package Paquete2;

import Paquete1.Clase2;

public class Clase3 {


public static void main(String[] args) {
Clase2 c2 = new Clase2();
System.out.println(c2.atributo);
}
}

Encapsulamiento y métodos accesores:


METODOS
// SETTERS = PONEDOR GETTERS = JALADOR
Clase proy_1:
package com.misproyectos.proy_1;
import java.util.Random;
import java.util.Scanner;
public class Proy_1 {
public static void main(String[] args){
Empleado empleado_1 = new Empleado();
empleado_1.setEdad(46);
System.out.println("Edad: " + empleado_1.getEdad());
}}
Clase Empleado:
package com.misproyectos.proy_1;

public class Empleado {


private int edad;
private String nombre;
public void setEdad(int _edad){
if (_edad > 18 && _edad < 80){
this.edad = _edad;
}
else{
System.out.println("Esta empresa no hacepta otras edades");
}
}
public int getEdad(){
return this.edad;
}
public void setNombre(String _nombre) {
this.nombre = _nombre;
}
public String getNombre() {
return nombre;
}
}
Constantes:
CLASE PROY_1:
package com.misproyectos.proy_1;

import java.util.Random;
import java.util.Scanner;

public class Proy_1 {


public static void main(String[] args){
Persona_1 p = new Persona_1("Jaime");
p.setDinero(5000000);
System.out.println("Nombre: " + p.getNombre() + " dinero: " +
p.getDinero());
}
}

CLASE PERSONA_1:
package com.misproyectos.proy_1;

public class Persona_1 {


private int dinero;
private final String nombre;

//Creamos un constructor para que no de error


public Persona_1(String _nombre){
this.nombre = _nombre;
}
public void setDinero(int dinero) {
this.dinero = dinero;
}
public int getDinero() {
return dinero;
}
public String getNombre() {
return nombre;
}
}
Miembro estático:
CLASE PROY_1:
package com.misproyectos.proy_1;

import java.util.Random;
import java.util.Scanner;

public class Proy_1 {


public static void main(String[] args){
Estatica i_1 = new Estatica();
Estatica i_2 = new Estatica();

System.out.println("i_1: " + i_1.normal);


System.out.println("i_2: " + i_2.normal);

i_1.normal = "Cambio de valor en i_1";


i_2.normal = "Cambio de valor en i_2";

System.out.println("i_1: " + i_1.normal);


System.out.println("i_2: " + i_2.normal);

System.out.println("");

System.out.println("i_1: " + i_1.estatico);


System.out.println("i_2: " + i_2.estatico);
i_1.estatico = "Nuevo valor desde i_1";
i_2.estatico = "Nuevo valor desde i_2";
System.out.println("i_1: " + i_1.estatico);
System.out.println("i_2: " + i_2.estatico);
}
}

CLASE ESTATICO:
package com.misproyectos.proy_1;

public class Estatica {


public String normal = "Inicializador normal";
public static String estatico = "Inicializador estatico";
}

Crear diagramas UML y convertirlo a


código java: Creamos un programa que nos entregue el área
y el perímetro de un cuadrilatero, utilizando un diagrama de un ULM.

CLASE CUADRILATERO:
package com.misproyectos.proy_1;

public class Cuadrilatero {

private float lado1;

private float lado2;

public Cuadrilatero(float lado1) {


this.lado1 = lado1;
this.lado2 = lado1;
}
public Cuadrilatero(float lado1, float lado2) {
this.lado1 = lado1;
this.lado2 = lado2;
}

public float getPerimetro() {


float perimetro;
perimetro = (this.lado1 + this.lado2) * 2;
return perimetro;
}

public float getArea() {


float area;
area = this.lado1 * this.lado2;
return area;
}
}

CLASE PRINSIPAL PROY_1:


package com.misproyectos.proy_1;

import java.util.Random;
import java.util.Scanner;

public class Proy_1 {


public static void main(String[] args){
float perimetro;
float area;
Cuadrilatero c;
System.out.println("Humano selecciona una de estas opciones:\n
1.Cuadrado \n 2: Rectangulo");
Scanner entra = new Scanner(System.in);
int opciones = entra.nextInt();
if(opciones == 1){
System.out.println("Humano. ingresa el tamaño del lado de tu
cuadrado: ");
c = new Cuadrilatero(entra.nextInt());
}else if(opciones == 2){
System.out.println("Humano!! Ingrsa el tamaño de los dos
lados de tu rectangulo");
c = new Cuadrilatero(entra.nextInt(), entra.nextInt());
}else{
c = new Cuadrilatero(0);
}
area = c.getArea();
perimetro = c.getPerimetro();
System.out.println("Humano tu area es: " + area + " y tu perimetro
es: " + perimetro);
}
}
Arreglo de objetos:

CLASE PROY_1:
package com.misproyectos.proy_1;

import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class Proy_1 {


public static void main(String[] args){
int cantAlumnos =
Integer.parseInt(JOptionPane.showInputDialog("Humano cuantos
alumnos tienes"));
Alumnos a[] = new Alumnos[cantAlumnos];

//Inicializamos todos los valores con un ciclo FOR


for (int i = 0; i < cantAlumnos; i++){
a[i] = new Alumnos(JOptionPane.showInputDialog("Ingresa el
nombre del Alumno"),JOptionPane.showInputDialog("Ingresa el aula
del alumno: ").charAt(0));

a[i].setCalificacion(Float.parseFloat(JOptionPane.showInputDialog("Ing
resa la calificacion")));
}
//Sacamos el promedio de cada uno
float suma = 0;
float promedio = 0;
int cantidadAlumnosPorAula = 0;
char aula = JOptionPane.showInputDialog("Dime que aula optener
su promedio").charAt(0);
for (int i = 0; i < cantAlumnos; i++){
if (a[i].getAula() == aula){
suma = suma + a[i].getCalificacion();
cantidadAlumnosPorAula++;
}
}
promedio = suma / cantidadAlumnosPorAula;
JOptionPane.showMessageDialog(null, promedio);
}
}

CLASE ALUMNOS:
package com.misproyectos.proy_1;

public class Alumnos {

private String nombre;

private char aula;

private float calificacion;

public Alumnos(String nombre, char aula) {


this.nombre = nombre;
this.aula = aula;
}

public void setCalificacion(float calficacion) {


if (calificacion > 10){
this.calificacion = 10;
}else if(calificacion < 0){
this.calificacion = 0;
}else{
this.calificacion = calficacion;
}
}
public float getCalificacion() {
return this.calificacion;
}

public char getAula() {


return this.aula;
}
}

Programación Orientada a Objetos


Herencia:

CLASE ESTUDIANTE:
private String codigoEstudiante;

private float calificacion;

public Estudiante(String nombre, String apellido,int edad, String


codigoEstudiante, float calificacion) {
super(nombre, apellido, edad);
this.codigoEstudiante = codigoEstudiante;
this.calificacion = calificacion;
}
public String getCodigoEstudiante() {
return this.codigoEstudiante;
}

public float getCalificacion() {


return this.calificacion;
}

public void muestraNombre() {


System.out.println("Nombre: " + this.getNombre());
}

public void muestraApellido() {


System.out.println("Apellido: " + this.getApellido());
}

public void muestraEdad() {


System.out.println("Edad: " + this.getEdad());
}
}

CLASE PERSONA:
package com.misproyectos.proy_1;

public class Persona {

private String nombre;

private String apellido;

private int edad;

public Persona(String nombre, String apellido,int edad) {


this.nombre = nombre;
this.apellido = apellido;
this.edad = edad;
}

public String getNombre() {


return this.nombre;
}

public String getApellido() {


return this.apellido;
}

public int getEdad() {


return this.edad;
}
}

CLASE PRINCIPAL PROY_1:


package com.misproyectos.proy_1;

import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class Proy_1 {


public static void main(String[] args){
Estudiante e = new Estudiante("Jaime", "Marin", 46, "ESP3266",
10);
e.muestraNombre();
e.muestraApellido();
e.muestraEdad();
}
}

(Programación Orientada a Objetos)


Sobreescritura de métodos:
CLASE PRINCIPAL PROY_1:
package com.misproyectos.proy_1;

public class Proy_1 {


public static void main(String[] args){
Animal a = new Animal();
a.comer();
a.correr();

Humano h = new Humano();


h.comer();
h.correr();

Pajaro p = new Pajaro();


p.comer();
p.vuela();
}
}

CLASE ANIMAL:
package com.misproyectos.proy_1;

public class Animal {

public void comer() {


System.out.println("Soy un animal y como");
}
public void correr() {
System.out.println("Soy un animar y corro");
}
}

CLASE HUMANO:
package com.misproyectos.proy_1;

public class Perro extends Animal {


@Override
public void comer() {
System.out.println("Los humanos me dan de comer");
}

@Override
public void correr() {
System.out.println("Los humanos corren con los perros");
}
}

CLASE PAJARO:
package com.misproyectos.proy_1;

public class Pajaro extends Animal {

@Override
public void comer() {
System.out.println("Nosotros comemos alpiste");
}

public void vuela() {


System.out.println("Y ademas volamos alto");
}
}
CLASE PERRO:
package com.misproyectos.proy_1;
public class Perro extends Animal {
@Override
public void comer() {
System.out.println("Los humanos me dan de comer");
}
@Override
public void correr() {
System.out.println("Los humanos corren con los perros");
}
}

 (POO) Clases y métodos abstractos:


-Deben ser SUPERCLASES(tener clases hijo).
-No pueden ser INSTANCIADAS
-Sirven para HEREDAR MÉTODOS Y ATRIBUTOS.
CLASE PRINCIPAL PROY_1:
package com.misproyectos.proy_1;

public class Proy_1 {


public static void main(String[] args){
Motocicletas m = new Motocicletas();
m.llantas();
Autos a = new Autos();
a.llantas();
Camiones c = new Camiones();
c.llantas();
}
}

CLASE ABSTRACTA AUTOMOTORES:


package com.misproyectos.proy_1;

//convertimos nuestra clase y metodo en ABSTRACTO


public abstract class Automotores {

public abstract void llantas();


}
CLASE ABSTRACTA GASOLINA:
package com.misproyectos.proy_1;

public class Camiones extends Dissel {


public void llantas() {
System.out.println("Yo tengo 8 llantas");
}
}

CLASE ABSTRACTA DISSEL:


package com.misproyectos.proy_1;

public abstract class Dissel extends Automotores {

public abstract void llantas();


}

CLASE MOTOCICLETA:
package com.misproyectos.proy_1;

public class Camiones extends Dissel {

public void llantas() {


System.out.println("Yo tengo 8 llantas");
}
}
CLASE AUTO:
package com.misproyectos.proy_1;

public class Autos extends Gasolina {


public void llantas() {
System.out.println("Yo me desplazo con 4 llantas");
}
}
CLASE CAMIONES:
package com.misproyectos.proy_1;
public class Camiones extends Dissel {

public void llantas() {


System.out.println("Yo tengo 8 llantas");
}
}

(POO) Polimorfismo: POLI: muchos o múltiples,


MORFISMO: Formas, esto quiere decir que se puede desarrollar una
cosa en varias con el mismo propósito.

Es una relación de tipo herencia, un objeto de la superclase puede


almacenar un objeto de cualquiera de sus subclases.
CLASE PRINCIPAL PROY_1:
package com.misproyectos.proy_1;

public class Proy_1 {


public static void main(String[] args){
Vehiculos v[] = new Vehiculos[4];
v[0] = new Vehiculos("AAAA", "Carro", "2011");
v[1] = new TipoDeportivo(8, "BBBB", "Ferrary", "2021");
v[2] = new TipoFurgoneta(10, "CCCC", "Chevrolet", "2000");
v[3] = new TipoTurismo(4, "DDDD", "Zusuki", "1975");

for(int i = 0; i < v.length; i++){


System.out.println(v[i].mostrarDatos());
}
}
}

CLASE VEHICULOS:
package com.misproyectos.proy_1;

public class Vehiculos {

protected String matricula;

protected String marca;

protected String modelo;

public Vehiculos(String matricula, String marca, String modelo) {


this.matricula = matricula;
this.marca = marca;
this.modelo = modelo;
}

public String getMatricula() {


return matricula;
}

public String getMarca() {


return marca;
}

public String getModelo() {


return modelo;
}

public String mostrarDatos() {


return "Matricula: " + this.matricula + " Marca: " + this.marca +
"Modelo: " + this.modelo;
}
}

CLASE TIPODEPORTIVO:
package com.misproyectos.proy_1;

public class TipoTurismo extends Vehiculos {

private int numeroPuertas;

public TipoTurismo(int numeroPuertas, String matricula, String


marca, String modelo) {
super(matricula, marca, modelo);
this.numeroPuertas = numeroPuertas;
}

@Override
public String mostrarDatos() {
return "Matricula: " + this.matricula + " Marca: " + this.marca +
"Modelo: " + this.modelo + " Numero de puertas: " +
this.numeroPuertas;
}
}

CLASE TIPOFURGUNETA:
package com.misproyectos.proy_1;

public class TipoFurgoneta extends Vehiculos {

private int carga;


public TipoFurgoneta(int carga, String matricula, String marca, String
modelo) {
super(matricula, marca, modelo);
this.carga = carga;
}

@Override
public String mostrarDatos() {
return "Matricula: " + this.matricula + " Marca: " + this.marca +
"Modelo: " + this.modelo + " Carga: " + this.carga;
}
}

CLASE TIPOTURISMO:
package com.misproyectos.proy_1;

public class TipoTurismo extends Vehiculos {

private int numeroPuertas;

public TipoTurismo(int numeroPuertas, String matricula, String


marca, String modelo) {
super(matricula, marca, modelo);
this.numeroPuertas = numeroPuertas;
}

@Override
public String mostrarDatos() {
return "Matricula: " + this.matricula + " Marca: " + this.marca +
"Modelo: " + this.modelo + " Numero de puertas: " +
this.numeroPuertas;
}
}
[Arreglos dinámicos con ArrayList]:
LISTA NORMAL ARRAYS:
package com.misproyectos.proy_1;

import javax.swing.JOptionPane;
public class Proy_1 {
public static void main(String[] args){
listaNormal();
}
private static void listaNormal() {
int numEle =
Integer.parseInt(JOptionPane.showInputDialog("Cuantos elementos
vas a ingresar"));
String lista[] = new String[numEle];
for (int i = 0; i < lista.length; i++){
lista[i] = new String();
lista[i] = JOptionPane.showInputDialog("Ingresa el valor del
elemento " + (i+1));
}
System.out.println("Resultados de la lista normal");
for (int i = 0; i < lista.length; i++){
System.out.println(lista[i]);
}
}
}
LISTA DINAMICA ARRAYS:
package com.misproyectos.proy_1;

import java.util.ArrayList;
import javax.swing.JOptionPane;

public class Proy_1 {


public static void main(String[] args){
listaDinamica();
}
private static void listaDinamica() {
//ArrayList <String> lista = new ArrayList<String>();
ArrayList <String> lista = new ArrayList<>();
char respuesta;
do{
lista.add(JOptionPane.showInputDialog("Ingresa el valor"));
respuesta = JOptionPane.showInputDialog("Quieres meter mas
elementos? s/n").charAt(0);
}while(respuesta == 's' || respuesta == 'S');
System.out.println("Resultados de la lista dinamica");
for (int i = 0; i < lista.size(); i++){
System.out.println(lista.get(i));
}
}
}
Ejercicio de POO Area de un terreno des
uniforme:
Hacer un programa que calcule el área de un terreno des-uniforme.
Para esto hay que dividir el terreno en triángulos y rectángulos. El
programa debe ser capaz de almacenar varios triángulos y rectángulos
para finalmente sumar sus áreas y obtener el área del terreno.

CLASE PRINCIPAL PROY_1:


package com.misproyectos.proy_1;

import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

/**
*Esta es nuestra clase principal a donde se accede al programa
* @author jaime
*/
public class Proy_1 {
static Scanner entra = new Scanner(System.in);
static ArrayList <Terreno> pedazoTerreno = new
ArrayList<Terreno>();
/**
*Simplemente se muestran los datos del area de cada instancia hija
y el
* area total.
* @param args
*/
public static void main(String[] args){
char respuesta;
int opcion;
do{
System.out.println("Que terreno quieres ingresar");
System.out.println("1: Triangulo");
System.out.println("2: Rectangulo");
opcion = entra.nextInt();
switch(opcion){
case 1: llenaTriangulo();
break;
case 2: llenaRectangulo();
break;
}
System.out.println("Introducir mas terreno a calcular? s/n");
respuesta = entra.next().charAt(0);
}while( respuesta == 's' || respuesta == 'S');
mostrarResultados();
}
/**
*Este metodo se encarga de recibir desde SCANNER 3 numeros y
colocarlos en
* la instancia (HIJA triangulo) y esa instancia agregarla al arreglo de
* terrenos.
*/
protected static void llenaTriangulo() {
double lado1,lado2,lado3;
System.out.println("Que medida tiene el lado 1 de tu triangulo");
lado1 = entra.nextDouble();
System.out.println("Que medida tiene el lado 2 de tu triangulo");
lado2 = entra.nextDouble();
System.out.println("Que medida tiene el lado 3 de tu triangulo");
lado3 = entra.nextDouble();

Triangulo t = new Triangulo(lado1,lado2,lado3);


pedazoTerreno.add(t);
}

/**
*Este metodo se encarga de recibir desde SCANNER 3 numeros y
colocarlos en
* la instancia (HIJA rectangulo) y esa instancia agregarla al arreglo
de
* terrenos.
*/
protected static void llenaRectangulo() {
double lado1,lado2;
System.out.println("Que medida tiene el lado 1 de tu rectangulo");
lado1 = entra.nextDouble();
System.out.println("Que medida tiene el lado 2 de tu rectangulo");
lado2 = entra.nextDouble();

Rectangulo r = new Rectangulo(lado1,lado2);


pedazoTerreno.add(r);
}

private static void mostrarResultados() {


double area = 0;
for ( Terreno t: pedazoTerreno ){
System.out.println( t.toString() + "Area " + t.area());
area += t.area();
}
System.out.println("El area total es: " + area);
}
}

CLASE TERRENO:
package com.misproyectos.proy_1;

public abstract class Terreno {

protected int numeroLados;

public Terreno(int numeroLados) {


this.numeroLados = numeroLados;
}

public int getNumeroLados() {


return numeroLados;
}

@Override
public String toString() {
return "Terreno{" + "Numero Lados=" + numeroLados + '}';
}
public abstract double area();
}

CLASE RECTANGULO:
package com.misproyectos.proy_1;

public class Rectangulo extends Terreno {

private double lado1;

private double lado2;

public Rectangulo(double lado1, double lado2) {


super(2);
this.lado1 = lado1;
this.lado2 = lado2;
}

public double getLado1() {


return lado1;
}

public double getLado2() {


return lado2;
}

@Override
public String toString() {
return "Rectangulo " + super.toString() + " {" + "lado1 = " +
this.lado1 + ", lado2=" + this.lado2 + '}';
}

public double area() {


return this.lado1 * this.lado2;
}
}

CLASE TRIANGULO:
package com.misproyectos.proy_1;

/**
*Esta es la clase se encarga de calcular el area del triangulo en base
a los
* lados de este.
* @author jaime
*/
public class Triangulo extends Terreno {

private double lado1;


private double lado2;
private double lado3;

/**
*Inicializamos los lados del triangulo
* @param lado1
* @param lado2
* @param lado3
*/
public Triangulo(double lado1, double lado2, double lado3) {
super(3);
this.lado1 = lado1;
this.lado2 = lado2;
this.lado3 = lado3;
}

/**
*
* @return
*/
public double getLado1() {
return lado1;
}

/**
*
* @return
*/
public double getLado2() {
return lado2;
}

/**
*
* @return
*/
public double getLado3() {
return lado3;
}

/**
*
* @return
*/
@Override
public String toString() {
return "Triangulo" + super.toString() + " {" + "lado1=" + lado1 + ",
lado2=" + lado2 + ", lado3=" + lado3 + '}';
}

/**
*Se calcula el area deusando la formula de HERON, y retorna el
area del
* triangulo
* @return
*/
public double area() {
double s = (this.lado1 + this.lado2 + this.lado3) / 2;
return Math.sqrt( s * (s - this.lado1) * (s - this.lado2) * (s -
this.lado3));
}
}

Que es una excepcion en java:


Son errores en tiempo de ejecución (cuando se está ejecutando el
programa) y esto ocurre cuando se produce un error en alguna de las
instrucciones de nuestro programa, como por ejemplo cuando se hace
una división entre cero, cuando no se abre correctamente un fichero,
etc.

Excepciones tipo throws en métodos:


OJO ESTO NO SE DEBE USAR Y SI LO
ENCUENTRA ES MEJOR MEJORARLO O
QUITARLE Y USAR (TRY CATCH).
Excepciones try catch y finally:
package com.programadornovato.proy1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class holaMundo {

public static void main(String[] args) {


/*
try{
leerArchivo();
}
catch( FileNotFoundException e ){
System.out.println("Archivo no encontrado:"+e);
}
catch ( IOException e ){
System.out.println("No se puede acceder a ese archivo:"+e);
}
catch ( Exception e){
System.out.println(e);
}
finally{
System.out.println("Yo me ejecuto si o si");
}
*/

//Exepciones no verificadas
try{
Integer num = null;
System.out.println(num.toString());
}
catch(NullPointerException e){
System.out.println("Debes inicializar tu objeto");
}
}

Interfaz grafica con JavaX Swing:


CLASE PRINCIPAL:
package com.mycompany.java;

public class Java {

public static void main(String[] args) {


Ventana v = new Ventana();
v.setVisible(true);
}
}

CLASE HIJO:
package com.mycompany.java;

import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.JFrame;

public class Ventana extends JFrame{

public Ventana() throws HeadlessException {


Dimension d = new Dimension(500,500);
this.setSize(d);
}
}
Interfaz grafica Agregar titulos y cerrar
nuestras ventanas:
CLASE PRINCIPAL:
package com.programadornovato.proy1;

public class holaMundo {


static void main(String[] args){
Ventana v=new Ventana("Si me buscas este es mi id"+getPID());
v.setVisible(true);
}
public static String getPID(){
return
java.lang.management.ManagementFactory.getRuntimeMXBean().get
Name();
}
}

CLASE HIJO:
package com.programadornovato.proy1;
import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.JFrame;

public class Ventana extends JFrame{


/*
public Ventana() throws HeadlessException {
Dimension d=new Dimension(500, 500);
this.setSize(d);
}
*/
public Ventana(String title) throws HeadlessException {
super(title);
Dimension d=new Dimension(500, 500);
this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Interfaz gráfica posicionar por


coordenadas nuestra ventana:
ESTO SE HACE PARA HACER EFECTOS DE MOVIMIENTOS EN LA
VENTANA
CLASE PRINCIPAL:
package com.mycompany.java;

import java.awt.HeadlessException;

public class Java {

public static void main(String[] args) throws HeadlessException,


InterruptedException {
Ventana v = new Ventana("Este es mi titulo" + getPID());
v.setVisible(true);
for(int i = 0; i < 10; i++){
Thread.sleep(200);
v.setLocation(i*30, i*30);
}
}
public static String getPID(){
return
java.lang.management.ManagementFactory.getRuntimeMXBean().get
Name();
}
}

CLASE HIJO;
package com.mycompany.java;

import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.JFrame;

public class Ventana extends JFrame{


public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
Dimension d = new Dimension(500,500);
this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//ACA POSICIONEMOS LA VENTANA
/*setLocation(300,300);*/
}
}

AHORA DARLE POSICION Y TAMAÑO:


CLSE HIJO:
package com.mycompany.java;

import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.JFrame;

public class Ventana extends JFrame{

public Ventana(String title) throws HeadlessException,


InterruptedException {
super(title);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//ACA POSICIONEMOS LA VENTANA
this.setBounds(300,300,500,500);
this.setLocationRelativeTo(null);
}
}

CLAE PADRE O PRINCIPAL:


package com.mycompany.java;

import java.awt.HeadlessException;

public class Java {

public static void main(String[] args) throws HeadlessException,


InterruptedException {
Ventana v = new Ventana("Este es mi titulo" + getPID());
v.setVisible(true);
}
public static String getPID(){
return
java.lang.management.ManagementFactory.getRuntimeMXBean().get
Name();
}
}

JPanel: Los JPanel sirven para ocultar todos los elementos de


una ventana.

package com.mycompany.java;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Ventana extends JFrame{

public Ventana(String title) throws HeadlessException,


InterruptedException {
super(title);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//ACA POSICIONEMOS LA VENTANA
this.setBounds(300,300,500,500);
this.setLocationRelativeTo(null);
iniciarPaneles();
}

protected void iniciarPaneles() {


JPanel contenedor = new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
JPanel panel_3 = new JPanel();
contenedor.add(panel_1);
contenedor.add(panel_2);
contenedor.add(panel_3);
//Darle colores
panel_1.setBackground(new Color(0,51,102));
panel_2.setBackground(Color.BLUE);
panel_3.setBackground(Color.YELLOW);
//Para el comportamiento de los contenedores osea JPanel
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
//Para ocultar algun Panel
panel_3.setVisible(false);
}

JLabel en un JPanel (Colocar etiquetas


en panles):
CLASE VENTANA HIJA:
package com.mycompany.java;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Ventana extends JFrame{


JPanel panel_1;
JPanel panel_2;
JPanel panel_3;
public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//ACA POSICIONEMOS LA VENTANA
this.setBounds(300,300,500,500);
this.setLocationRelativeTo(null);
iniciarPaneles();
iniciaEtiquetas();
}

protected void iniciarPaneles() {


JPanel contenedor = new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);
this.panel_1 = new JPanel();
this.panel_2 = new JPanel();
this.panel_3 = new JPanel();
contenedor.add(panel_1);
contenedor.add(panel_2);
contenedor.add(panel_3);
//Darle colores
this.panel_1.setBackground(new Color(0,51,102));
this.panel_2.setBackground(Color.BLUE);
this.panel_3.setBackground(Color.YELLOW);
//Para el comportamiento de los contenedores osea JPanel
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
//Para ocultar algun Panel
//panel_3.setVisible(false);
}

protected void iniciaEtiquetas() {


JLabel e_1 = new JLabel("<html>Hola humano soy etiqueta
1</html>");
JLabel e_2 = new JLabel("<html>Hola humano soy etiqueta
2</html>");
JLabel e_3 = new JLabel("<html>Hola humano soy etiqueta
3</html>");
//ADERIR LAS ETIQUETAS A LOS PANELES
this.panel_1.add(e_1);
this.panel_2.add(e_2);
this.panel_3.add(e_3);
//DARLE COLOR A LAS ETIQUETAS
e_1.setForeground(Color.white);
e_2.setForeground(Color.white);
e_3.setForeground(Color.white);
//QUITAMOS EL LAYAOUT
this.panel_1.setLayout(null);
this.panel_2.setLayout(null);
this.panel_3.setLayout(null);
//AHORA LE DAMOS UN ANCHO Y UNA POSICION A LA
ETIQUETA
e_1.setBounds(10, 100, 90, 60);
e_2.setBounds(10, 100, 90, 60);
e_3.setBounds(10, 100, 90, 60);
//CAMBIAR EL TEXTO DE LA ETIQUETA
e_1.setText("<html>Hola Jaime Hernan</html>");
//AHORA VAMOS A OCULATAR UNO DE LOS PANELES en este
caso el panel 2
this.panel_2.setVisible(false);
}

CLASE PADRE:
package com.mycompany.java;

import java.awt.HeadlessException;

public class Java {

public static void main(String[] args) throws HeadlessException,


InterruptedException {
Ventana v = new Ventana("Este es mi titulo" + getPID());
v.setVisible(true);
}
public static String getPID(){
return
java.lang.management.ManagementFactory.getRuntimeMXBean().get
Name();
}
}

ARGS JAVA ¿QUE ES? Y COMO CREAR


EJECUTABLE NETBEANS
ESTE TEMA ES PARA COMO CREAR UN EJECUTABLE QUE
CORRA EN CUALQUIER SISTEMA OPERATIVO.

CLASE VENTANA:
package com.programadornovato.proy1;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Ventana extends JFrame{
JPanel panel1;
JPanel panel2;
JPanel panel3;
JLabel e1;
JLabel e2;
JLabel e3;
/*
public Ventana() throws HeadlessException {
Dimension d=new Dimension(500, 500);
this.setSize(d);
}
*/
public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
//Dimension d=new Dimension(500, 500);
//this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//this.setLocation(300, 300);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
iniciarPaneles();
inicaEtiquetas();
}
protected void iniciarPaneles() {
JPanel contenedor=new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);
this.panel1=new JPanel();
this.panel2=new JPanel();
this.panel3=new JPanel();
contenedor.add(this.panel1);
contenedor.add(this.panel2);
contenedor.add(this.panel3);
this.panel1.setBackground(new Color(0, 51, 102));
this.panel2.setBackground(new Color(0, 102, 255));
this.panel3.setBackground(new Color(255, 0, 255));
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
//this.panel3.setVisible(false);
}
protected void inicaEtiquetas() {
e1=new JLabel("<html>Hola Humano soy la etiqueta1</html>");
e2=new JLabel("<html>Hola Humano soy la etiqueta2</html>");
e3=new JLabel("<html>Hola Humano soy la etiqueta3</html>");
this.panel1.add(e1);
this.panel2.add(e2);
this.panel3.add(e3);
e1.setForeground(Color.white);
e2.setForeground(Color.white);
e3.setForeground(Color.white);
this.panel1.setLayout(null);
this.panel2.setLayout(null);
this.panel3.setLayout(null);
e1.setBounds(10, 100, 90, 60);
e2.setBounds(10, 100, 90, 60);
e3.setBounds(10, 100, 90, 60);
e1.setText("<html>Hola humano</html>");
this.panel2.setVisible(false);
}
public void setTextos(String textos[]){
this.e1.setText(textos[0]);
this.e2.setText(textos[1]);
this.e3.setText(textos[2]);
}
}

CLASE PRINCIPAL:
package com.programadornovato.proy1;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class holaMundo {
public static void main(String[] args) throws HeadlessException,
InterruptedException{
Ventana v=new Ventana("Si me buscas este es mi id"+getPID());
v.setVisible(true);
if(args.length>0){
v.setTextos(args);
}
}
public static String getPID(){
return
java.lang.management.ManagementFactory.getRuntimeMXBean().get
Name();
}
}
Alinear etiquetas (Alignment label):
package com.programadornovato.proy1;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.HeadlessException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Ventana extends JFrame{
JPanel panel1;
JPanel panel2;
JPanel panel3;
JLabel e1;
JLabel e2;
JLabel e3;
public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
//Dimension d=new Dimension(500, 500);
//this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//this.setLocation(300, 300);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
iniciarPaneles();
inicaEtiquetas();
}
protected void iniciarPaneles() {
JPanel contenedor=new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);
this.panel1=new JPanel();
this.panel2=new JPanel();
this.panel3=new JPanel();
contenedor.add(this.panel1);
contenedor.add(this.panel2);
contenedor.add(this.panel3);
this.panel1.setBackground(new Color(0, 51, 102));
this.panel2.setBackground(new Color(0, 102, 255));
this.panel3.setBackground(new Color(255, 0, 255));
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
//this.panel3.setVisible(false);
}
protected void inicaEtiquetas() {
e1=new JLabel("<html>Hola1</html>");
e2=new JLabel("<html>Hola2</html>");
e3=new JLabel("<html>Hola3</html>");
this.panel1.add(e1);
this.panel2.add(e2);
this.panel3.add(e3);
e1.setForeground(Color.white);
e2.setForeground(Color.white);
e3.setForeground(Color.white);
this.panel1.setLayout(null);
this.panel2.setLayout(null);
this.panel3.setLayout(null);
e1.setBounds(10, 100, 120, 60);
e2.setBounds(10, 100, 120, 60);
e3.setBounds(10, 100, 120, 60);
//e1.setText("<html>Hola humano</html>");
//this.panel2.setVisible(false);
e1.setOpaque(true);
e2.setOpaque(true);
e3.setOpaque(true);
e1.setBackground(Color.black);
e2.setBackground(Color.black);
e3.setBackground(Color.black);
/*
HorizontalAlignment
CENTER = 0;
LEFT = 2;
RIGHT = 4;
VerticalAlignment
TOP = 1;
BOTTOM = 3;
*/
e1.setHorizontalAlignment(SwingConstants.LEFT);
e2.setHorizontalAlignment(SwingConstants.CENTER);
e3.setHorizontalAlignment(SwingConstants.RIGHT);
e1.setVerticalAlignment(SwingConstants.TOP);
e2.setVerticalAlignment(SwingConstants.BOTTOM);
}
public void setTextos(String textos[]){
this.e1.setText(textos[0]);
this.e2.setText(textos[1]);
this.e3.setText(textos[2]);
}
}

Agregar fuentes a nuestras etiquetas


(font labels):
package com.programadornovato.proy1;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.HeadlessException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Ventana extends JFrame{
JPanel panel1;
JPanel panel2;
JPanel panel3;
JLabel e1;
JLabel e2;
JLabel e3;
/*
public Ventana() throws HeadlessException {
Dimension d=new Dimension(500, 500);
this.setSize(d);
}
*/
public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
//Dimension d=new Dimension(500, 500);
//this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//this.setLocation(300, 300);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
iniciarPaneles();
inicaEtiquetas();
}
protected void iniciarPaneles() {
JPanel contenedor=new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);
this.panel1=new JPanel();
this.panel2=new JPanel();
this.panel3=new JPanel();
contenedor.add(this.panel1);
contenedor.add(this.panel2);
contenedor.add(this.panel3);
this.panel1.setBackground(new Color(0, 51, 102));
this.panel2.setBackground(new Color(0, 102, 255));
this.panel3.setBackground(new Color(255, 0, 255));
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
//this.panel3.setVisible(false);
}
protected void inicaEtiquetas() {
e1=new JLabel("<html>Hola1</html>");
e2=new JLabel("<html>Hola2</html>");
e3=new JLabel("<html>Hola3</html>");
this.panel1.add(e1);
this.panel2.add(e2);
this.panel3.add(e3);
e1.setForeground(Color.white);
e2.setForeground(Color.white);
e3.setForeground(Color.white);
this.panel1.setLayout(null);
this.panel2.setLayout(null);
this.panel3.setLayout(null);
e1.setBounds(10, 100, 120, 60);
e2.setBounds(10, 100, 120, 60);
e3.setBounds(10, 100, 120, 60);
//e1.setText("<html>Hola humano</html>");
//this.panel2.setVisible(false);
e1.setOpaque(true);
e2.setOpaque(true);
e3.setOpaque(true);
e1.setBackground(Color.black);
e2.setBackground(Color.black);
e3.setBackground(Color.black);
/*
HorizontalAlignment
CENTER = 0;
LEFT = 2;
RIGHT = 4;
VerticalAlignment
TOP = 1;
BOTTOM = 3;
*/
e1.setHorizontalAlignment(SwingConstants.LEFT);
e2.setHorizontalAlignment(SwingConstants.CENTER);
e3.setHorizontalAlignment(SwingConstants.RIGHT);
e1.setVerticalAlignment(SwingConstants.TOP);
e2.setVerticalAlignment(SwingConstants.BOTTOM);
/*
name
DIALOG = "Dialog";
DIALOG_INPUT = "DialogInput";
SANS_SERIF = "SansSerif";
SERIF = "Serif";
style
PLAIN = 0;
BOLD = 1;
ITALIC = 2;
*/
e1.setFont(new Font("Megatron",Font.ITALIC,15));
e2.setFont(new Font("Face Your Fears",Font.BOLD,20));
e3.setFont(new Font("ObelixPro",Font.PLAIN,25));
}
public void setTextos(String textos[]){
this.e1.setText(textos[0]);
this.e2.setText(textos[1]);
this.e3.setText(textos[2]);
}
}

Agregar imágenes a nuestras etiquetas


(jlabel + images):
package com.programadornovato.proy1;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.Image;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
/**
*
* @author eugenio
*/
public class Ventana extends JFrame{
JPanel panel1;
JPanel panel2;
JPanel panel3;
JLabel e1;
JLabel e2;
JLabel e3;
/*
public Ventana() throws HeadlessException {
Dimension d=new Dimension(500, 500);
this.setSize(d);
}
*/
public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
//Dimension d=new Dimension(500, 500);
//this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//this.setLocation(300, 300);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
iniciarPaneles();
inicaEtiquetas();
}
protected void iniciarPaneles() {
JPanel contenedor=new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);
this.panel1=new JPanel();
this.panel2=new JPanel();
this.panel3=new JPanel();
contenedor.add(this.panel1);
contenedor.add(this.panel2);
contenedor.add(this.panel3);
this.panel1.setBackground(new Color(0, 51, 102));
this.panel2.setBackground(new Color(0, 102, 255));
this.panel3.setBackground(new Color(255, 0, 255));
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
//this.panel3.setVisible(false);
}
protected void inicaEtiquetas() {
//ImageIcon imagen1=new ImageIcon("images/netbeans 11.png");
//ImageIcon imagenEscala=new
ImageIcon(imagen1.getImage().getScaledInstance(60, 60,
Image.SCALE_DEFAULT));
e1=new JLabel("<html>Hola1</html>",new ImageIcon(new
ImageIcon("images/netbeans
11.png").getImage().getScaledInstance(60, 60,
Image.SCALE_DEFAULT)),SwingConstants.LEFT);
e2=new JLabel("<html>Hola2</html>");
e3=new JLabel("h");
this.panel1.add(e1);
this.panel2.add(e2);
this.panel3.add(e3);
e1.setForeground(Color.white);
e2.setForeground(Color.white);
e3.setForeground(Color.white);
this.panel1.setLayout(null);
this.panel2.setLayout(null);
this.panel3.setLayout(null);
e1.setBounds(10, 100, 120, 60);
e2.setBounds(10, 100, 120, 60);
e3.setBounds(10, 100, 120, 60);
//e1.setText("<html>Hola humano</html>");
//this.panel2.setVisible(false);
e1.setOpaque(false);
e2.setOpaque(true);
e3.setOpaque(true);
e1.setBackground(Color.black);
e2.setBackground(Color.black);
e3.setBackground(Color.black);
/*
HorizontalAlignment
CENTER = 0;
LEFT = 2;
RIGHT = 4;
VerticalAlignment
TOP = 1;
BOTTOM = 3;
*/
e1.setHorizontalAlignment(SwingConstants.LEFT);
e2.setHorizontalAlignment(SwingConstants.CENTER);
e3.setHorizontalAlignment(SwingConstants.RIGHT);
e1.setVerticalAlignment(SwingConstants.TOP);
e2.setVerticalAlignment(SwingConstants.BOTTOM);
/*
name
DIALOG = "Dialog";
DIALOG_INPUT = "DialogInput";
SANS_SERIF = "SansSerif";
SERIF = "Serif";
style
PLAIN = 0;
BOLD = 1;
ITALIC = 2;
*/
e1.setFont(new Font("Megatron",Font.ITALIC,15));
e2.setFont(new Font("Face Your Fears",Font.BOLD,20));
e3.setFont(new Font("ObelixPro",Font.PLAIN,25));
e2.setIcon(new ImageIcon(new ImageIcon("images/netbeans
11.png").getImage().getScaledInstance(60, 60,
Image.SCALE_DEFAULT)));
e3.setIcon(new ImageIcon(new ImageIcon("images/netbeans
11.png").getImage().getScaledInstance(60, 60,
Image.SCALE_DEFAULT)));
}
public void setTextos(String textos[]){
this.e1.setText(textos[0]);
this.e2.setText(textos[1]);
this.e3.setText(textos[2]);
}
}

Lista de etiquetas y de paneles: Vamos a


reducir el codigo con arreglos.
package com.mycompany.java;

import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.Image;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Ventana extends JFrame{


ArrayList <JPanel> panel = new ArrayList <JPanel>();
ArrayList <JLabel> etiqueta = new ArrayList <JLabel>();
//Declaramos una variable con la cantidad de paneles que vamos a
tener
int num = 4;

public Ventana(String title) throws HeadlessException,


InterruptedException {
super(title);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//ACA POSICIONEMOS LA VENTANA
this.setBounds(300,300,500,500);
this.setLocationRelativeTo(null);
//LE DECIMOS A EL USUARIO CUANTOS PANELES QUIERE
this.num =
Integer.parseInt(JOptionPane.showInputDialog("Humano cuantos
paneles quieres"));
iniciarPaneles();
iniciaEtiquetas();
}

protected void iniciarPaneles() {


JPanel contenedor = new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);

//vamos a inicializar cada uno de nuestros paneles


for (int i = 0; i < this.num; i++){
this.panel.add(new JPanel());
//VAMMOS A METER LOS PANELES DENTRO DE NUESTRO
CONTENEDOR
contenedor.add(this.panel.get(i));
//AHORA LE DAMOS COLOR A LOS PANELES
this.panel.get(i).setBackground(new Color(i*50,i*50,i*50));
}
//AHORA TOMAMOS EL CONTENEDOR Y LE DECIMOS CUAL
VA SER SU DISEÑO
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
}

protected void iniciaEtiquetas() {


for (int i = 0; i < this.num; i++){
this.etiqueta.add(new JLabel("Hola" + (i+1), new ImageIcon(new
ImageIcon("images/ubuntu.jpg").getImage().getScaledInstance(60, 60,
Image.SCALE_DEFAULT)) , SwingConstants.RIGHT ));
this.etiqueta.get(i).setForeground(Color.white);
this.panel.get(i).add(this.etiqueta.get(i));
}
}
//CREAMOS UN NUEVO METODO
public void setTextos(String textos[]){

}
}

Crear un boton (AWT Button VS Swing


JButton):
package com.mycompany.java;

import java.awt.Button;
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Ventana extends JFrame{


ArrayList <JPanel> panel = new ArrayList <JPanel>();
ArrayList <JLabel> etiqueta = new ArrayList <JLabel>();
JButton b1;
Button awtBoton;
//Declaramos una variable con la cantidad de paneles que vamos a
tener
int num = 4;

public Ventana(String title) throws HeadlessException,


InterruptedException {
super(title);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//ACA POSICIONEMOS LA VENTANA
this.setBounds(300,300,500,500);
this.setLocationRelativeTo(null);
//CREAMOS UN NUEVO METODO
iniciarBotones();
}

protected void iniciarPaneles() {


JPanel contenedor = new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);

//vamos a inicializar cada uno de nuestros paneles


for (int i = 0; i < this.num; i++){
this.panel.add(new JPanel());
//VAMMOS A METER LOS PANELES DENTRO DE NUESTRO
CONTENEDOR
contenedor.add(this.panel.get(i));
//AHORA LE DAMOS COLOR A LOS PANELES
this.panel.get(i).setBackground(new Color(i*50,i*50,i*50));
}
//AHORA TOMAMOS EL CONTENEDOR Y LE DECIMOS CUAL
VA SER SU DISEÑO
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
}

protected void iniciaEtiquetas() {


for (int i = 0; i < this.num; i++){
this.etiqueta.add(new JLabel("Hola" + (i+1), new ImageIcon(new
ImageIcon("images/ubuntu.jpg").getImage().getScaledInstance(60, 60,
Image.SCALE_DEFAULT)) , SwingConstants.RIGHT ));
this.etiqueta.get(i).setForeground(Color.white);
this.panel.get(i).add(this.etiqueta.get(i));
}
}
//CREAMOS UN NUEVO METODO
public void setTextos(String textos[]){

protected void iniciarBotones() {


//INSTANCIAMOS LOS BOTONES
b1 = new JButton("Suscribete");
awtBoton = new Button("Boton AWT");
JPanel contenedor = new JPanel();
this.getContentPane().add(contenedor);
//AGREGAMOS LOS BOTONES AL CONTENEDOR
contenedor.add(b1);
contenedor.add(awtBoton);
//POCISIONAMOS EL BOTON
contenedor.setLayout(null);
b1.setBounds(100, 180, 150, 30);
awtBoton.setBounds(150, 300, 160, 40);
//ACA CAMBIAMOS EL TEXTO
b1.setText("Boton Subir");
//DESHABILITAMOS O HABILITAR EL BOTON
b1.setEnabled(true);
//EVENTOS A EL BOTON (Alt + J) Y SE ACTIVA EL BOTON
//b1.setMnemonic('J');
b1.setMnemonic(KeyEvent.VK_J);
}
}
CAMBIAR COLOR Y AGREGAR UNA
IMAGEN A NUESTRO BOTÓN:
package com.mycompany.java;

import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Ventana extends JFrame{


ArrayList <JPanel> panel = new ArrayList <JPanel>();
ArrayList <JLabel> etiqueta = new ArrayList <JLabel>();
JButton b1;
Button awtBoton;
//Declaramos una variable con la cantidad de paneles que vamos a
tener
int num = 4;

public Ventana(String title) throws HeadlessException,


InterruptedException {
super(title);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//ACA POSICIONEMOS LA VENTANA
this.setBounds(300,300,500,500);
this.setLocationRelativeTo(null);
//CREAMOS UN NUEVO METODO
iniciarBotones();
}

protected void iniciarPaneles() {


JPanel contenedor = new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);

//vamos a inicializar cada uno de nuestros paneles


for (int i = 0; i < this.num; i++){
this.panel.add(new JPanel());
//VAMMOS A METER LOS PANELES DENTRO DE NUESTRO
CONTENEDOR
contenedor.add(this.panel.get(i));
//AHORA LE DAMOS COLOR A LOS PANELES
this.panel.get(i).setBackground(new Color(i*50,i*50,i*50));
}
//AHORA TOMAMOS EL CONTENEDOR Y LE DECIMOS CUAL
VA SER SU DISEÑO
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
}

protected void iniciaEtiquetas() {


for (int i = 0; i < this.num; i++){
this.etiqueta.add(new JLabel("Hola" + (i+1), new ImageIcon(new
ImageIcon("images/ubuntu.jpg").getImage().getScaledInstance(60, 60,
Image.SCALE_DEFAULT)) , SwingConstants.RIGHT ));
this.etiqueta.get(i).setForeground(Color.white);
this.panel.get(i).add(this.etiqueta.get(i));
}
}
//CREAMOS UN NUEVO METODO
public void setTextos(String textos[]){

protected void iniciarBotones() {


//INSTANCIAMOS LOS BOTONES
b1 = new JButton("Suscribete");
JPanel contenedor = new JPanel();
this.getContentPane().add(contenedor);
//AGREGAMOS LOS BOTONES AL CONTENEDOR
contenedor.add(b1);
//POCISIONAMOS EL BOTON
contenedor.setLayout(null);
b1.setBounds(100, 100, 250, 50);
//ACA CAMBIAMOS EL TEXTO
b1.setText("Boton Subir");
//DESHABILITAMOS O HABILITAR EL BOTON
b1.setEnabled(true);
//EVENTOS A EL BOTON (Alt + J) Y SE ACTIVA EL BOTON
//b1.setMnemonic('J');
b1.setMnemonic(KeyEvent.VK_J);
//CAMBIAMOS LA FUENTE
b1.setFont(new Font(Font.SANS_SERIF,Font.BOLD, 15));
//CAMBIAR FONDO DEL BOTON
b1.setBackground(new Color(51, 255, 51));
//COLOCAMOS EL COLOR DE FUENTE
b1.setForeground(Color.WHITE);
//PONEMOS UNA IMAGEN AL BOTON Y LA HACEMOS MAS
PEQUEÑA
b1.setIcon(new ImageIcon(new
ImageIcon("images/ubuntu.jpg").getImage().getScaledInstance(30,30,I
mage.SCALE_SMOOTH)));
}
}

RADIOBUTTON (Grupo de RadioButton):


package com.mycompany.java;

import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;

public class Ventana extends JFrame{


ArrayList <JPanel> panel = new ArrayList <JPanel>();
ArrayList <JLabel> etiqueta = new ArrayList <JLabel>();
ArrayList <JRadioButton> listaRadioBoton = new ArrayList
<JRadioButton>();
//DECLARAMOS EL CONTENEDOR DE FORMA GLOBAL
JPanel contenedor = new JPanel();
JButton b1;
Button awtBoton;
//Declaramos una variable con la cantidad de paneles que vamos a
tener
int num = 4;

public Ventana(String title) throws HeadlessException,


InterruptedException {
super(title);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//ACA POSICIONEMOS LA VENTANA
this.setBounds(300,300,500,500);
this.setLocationRelativeTo(null);
this.getContentPane().add(contenedor);
contenedor.setLayout(null);
//CREAMOS UN NUEVO METODO
iniciarRadio();
}
private void iniciarRadio() {
//ACA SELECCIONAMOS SOLO UNO DE LOS RADIOBUTTON
ButtonGroup grupo = new ButtonGroup();
String textoOpciones[] =
{
"Opcion 1",
"Opcion 2",
"Opcion 3"
};
for (int i = 0; i < textoOpciones.length; i++){
//INICIALIZAMOS NUESTRO RADIO BUTTON
listaRadioBoton.add(new JRadioButton());
listaRadioBoton.get(i).setText(textoOpciones[i]);
//LO POCICIONAMOS PARA QUE APAREZCA
listaRadioBoton.get(i).setBounds(100, 100+(i*50),350, 50);
//CAMBIAMOS LA FUENTE A EL RADIOBUTTON
listaRadioBoton.get(i).setFont(new Font(Font.SERIF,
Font.BOLD, 30));
//SELECCIONAMOS UN RADIOBUTTON POR DEFAULT
if (i == 2){
listaRadioBoton.get(i).setSelected(true);
}
//LLAMAMOS CADA UNO DE NUESTROS BUTTONGROUP
grupo.add(listaRadioBoton.get(i));
//GREGAMOS AL CONTENEDOR
this.contenedor.add(listaRadioBoton.get(i));
}
/*
JRadioButton rb = new JRadioButton("Opcion 1");
rb.setBounds(100, 100, 250, 50);
this.contenedor.add(rb);
*/
}

protected void iniciarPaneles() {


JPanel contenedor = new JPanel();
this.getContentPane().add(contenedor);
contenedor.setBackground(Color.red);

//vamos a inicializar cada uno de nuestros paneles


for (int i = 0; i < this.num; i++){
this.panel.add(new JPanel());
//VAMMOS A METER LOS PANELES DENTRO DE
NUESTRO CONTENEDOR
contenedor.add(this.panel.get(i));
//AHORA LE DAMOS COLOR A LOS PANELES
this.panel.get(i).setBackground(new Color(i*50,i*50,i*50));
}
//AHORA TOMAMOS EL CONTENEDOR Y LE DECIMOS CUAL
VA SER SU DISEÑO
contenedor.setLayout(new BoxLayout(contenedor,
BoxLayout.X_AXIS));
}

protected void iniciaEtiquetas() {


for (int i = 0; i < this.num; i++){
this.etiqueta.add(new JLabel("Hola" + (i+1), new ImageIcon(new
ImageIcon("images/ubuntu.jpg").getImage().getScaledInstance(60, 60,
Image.SCALE_DEFAULT)) , SwingConstants.RIGHT ));
this.etiqueta.get(i).setForeground(Color.white);
this.panel.get(i).add(this.etiqueta.get(i));
}
}
//CREAMOS UN NUEVO METODO
public void setTextos(String textos[]){

}
}

CAMPO DE TEXTO (JTextField):


package com.programadornovato.proy1;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Ventana extends JFrame{
ArrayList <JPanel> panel=new ArrayList<JPanel>();
ArrayList <JLabel> etiqueta=new ArrayList<JLabel>();
ArrayList <JRadioButton> listaRb=new ArrayList<JRadioButton>();
JPanel contenedor=new JPanel();
JButton b1;
int num=4;
public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
//Dimension d=new Dimension(500, 500);
//this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//this.setLocation(300, 300);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
this.getContentPane().add(contenedor);
//contenedor.setLayout(null);
//this.num= Integer.parseInt(JOptionPane.showInputDialog("Humano
cuantos paneles quieres"));
//iniciarPaneles();
//inicaEtiquetas();
//iniciarBotones();
//iniciarRadio();
iniciaCampoTexto();
}
public void iniciaCampoTexto(){
JTextField campoText=new JTextField();
campoText.setText("HHHHHHHHHHHHHHHHHHHH");
JTextField campoText2=new JTextField();
campoText2.setText("HHHHHHHHHHHHHHHHHHHH");
campoText2.setFont(new Font(Font.SERIF,Font.BOLD,20));
campoText2.setBackground(new Color(0, 10, 255));
campoText2.setForeground(new Color(255, 240, 0));
//campoText.setBounds(100, 100, 300, 25);
campoText.setColumns(20);
campoText2.setColumns(20);
this.contenedor.add(campoText);
this.contenedor.add(campoText2);
}
}

AREA DE TEXTO CON


SCROLL(JTextArea):
package com.programadornovato.proy1;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;

public class Ventana extends JFrame{


ArrayList <JPanel> panel=new ArrayList<JPanel>();
ArrayList <JLabel> etiqueta=new ArrayList<JLabel>();
ArrayList <JRadioButton> listaRb=new ArrayList<JRadioButton>();
JPanel contenedor=new JPanel();
JButton b1;
int num=4;
public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
//Dimension d=new Dimension(500, 500);
//this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//this.setLocation(300, 300);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
this.getContentPane().add(contenedor);
contenedor.setLayout(null);
//this.num= Integer.parseInt(JOptionPane.showInputDialog("Humano
cuantos paneles quieres"));
//iniciarPaneles();
//inicaEtiquetas();
//iniciarBotones();
//iniciarRadio();
//iniciaCampoTexto();
iniciaAreaTexto();
}
public void iniciaAreaTexto(){
JTextArea areaTexto=new JTextArea();
//areaTexto.setBounds(100, 100, 300, 150);
areaTexto.setText("Humano este es un texto");
areaTexto.append("\nHumano aqui hay mas texto");
areaTexto.append("\nHumano aqui hay mas texto\n");
areaTexto.setEnabled(true);
areaTexto.setEditable(true);
JScrollPane scroll=new JScrollPane(areaTexto);
scroll.setBounds(100, 100, 300, 150);
this.contenedor.add(scroll);
System.out.println(areaTexto.getText());
}
}

LISTA DESPLEGABLE (JComboBox):


package com.programadornovato.proy1;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;

public class Ventana extends JFrame{


ArrayList <JPanel> panel=new ArrayList<JPanel>();
ArrayList <JLabel> etiqueta=new ArrayList<JLabel>();
ArrayList <JRadioButton> listaRb=new ArrayList<JRadioButton>();
JPanel contenedor=new JPanel();
JButton b1;
int num=4;
public Ventana(String title) throws HeadlessException,
InterruptedException {
super(title);
//Dimension d=new Dimension(500, 500);
//this.setSize(d);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//this.setLocation(300, 300);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
this.getContentPane().add(contenedor);
contenedor.setLayout(null);
//this.num= Integer.parseInt(JOptionPane.showInputDialog("Humano
cuantos paneles quieres"));
//iniciarPaneles();
//inicaEtiquetas();
//iniciarBotones();
//iniciarRadio();
//iniciaCampoTexto();
//iniciaAreaTexto();
iniciaListaDesplegable();
}
public void iniciaListaDesplegable(){
String lenguajes[]={
"Java",
"PHP",
"JavaScript",
"C"
};
JComboBox listaDesplegable=new JComboBox(lenguajes);
listaDesplegable.setBounds(10, 10, 300, 30);
//listaDesplegable.setSelectedItem("JavaScript");
listaDesplegable.addItem("VisualBasic");
listaDesplegable.setSelectedIndex(3);
this.contenedor.add(listaDesplegable);
System.out.println("Humano este es el texto
seleccionado:"+listaDesplegable.getSelectedItem());
System.out.println("Humano este es el texto
seleccionado:"+listaDesplegable.getSelectedIndex());
}
}
EVENTOS CLICK EN BOTON:
CLASE PADRE:
package com.mycompany.java;

import java.awt.HeadlessException;

public class Java {

public static void main(String[] args) throws HeadlessException,


InterruptedException {
Ventana v = new Ventana("Este es mi titulo" + getPID());
v.setVisible(true);
//VALIDAMOS QUE SE RECIBAN LOS ARGUMENTOS args
if(args.length > 0){
//VAMOS A LLAMAR NUESTRA FUNCION setTextos
// v.setTextos(args);
}
}
public static String getPID(){
return
java.lang.management.ManagementFactory.getRuntimeMXBean().get
Name();
}
}
CLASE HIJO:
package com.programadornovato.proy1;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;

public class Ventana extends JFrame{


JPanel contenedor;
JButton boton;
JLabel etiqueta;
JTextField caja;
public Ventana(){
contenedor=new JPanel();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
this.getContentPane().add(this.contenedor);
this.contenedor.setLayout(null);
boton =new JButton("Humano pon tu miserable nombre para
saludarte");
contenedor.add(boton);
boton.setBounds(10, 10, 400, 30);
caja =new JTextField();
contenedor.add(caja);
caja.setBounds(10, 50, 400, 30);
etiqueta =new JLabel();
contenedor.add(etiqueta);
etiqueta.setBounds(10, 100, 400, 30);
ActionListener accion=new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("Hola");
etiqueta.setText("Hola "+caja.getText());
}
};
boton.addActionListener(accion);
}
}

EVENTOS DEL RATON (MouseListener):


package com.programadornovato.proy1;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;

public class Ventana extends JFrame{


JPanel contenedor;
JButton boton;
JLabel etiqueta;
JTextField caja;
public Ventana(){
contenedor=new JPanel();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
this.getContentPane().add(this.contenedor);
this.contenedor.setLayout(null);
//accionBoton();
accionRaton();
}
protected void accionRaton(){
boton =new JButton("Humano!!! ponte jugar con el raton aqui");
contenedor.add(boton);
boton.setBounds(10, 10, 400, 30);
caja =new JTextField();
contenedor.add(caja);
caja.setBounds(10, 50, 400, 30);
MouseListener l = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
caja.setText("mouseClicked");
}
@Override
public void mousePressed(MouseEvent e) {
caja.setText("mousePressed");
}
@Override
public void mouseReleased(MouseEvent e) {
caja.setText("mouseReleased");
}
@Override
public void mouseEntered(MouseEvent e) {
caja.setText("mouseEntered");
}
@Override
public void mouseExited(MouseEvent e) {
caja.setText("mouseExited");
}
};
boton.addMouseListener(l);
}
private void accionBoton() {
boton =new JButton("Humano pon tu miserable nombre para
saludarte");
contenedor.add(boton);
boton.setBounds(10, 10, 400, 30);
caja =new JTextField();
contenedor.add(caja);
caja.setBounds(10, 50, 400, 30);
etiqueta =new JLabel();
contenedor.add(etiqueta);
etiqueta.setBounds(10, 100, 400, 30);
ActionListener accion=new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("Hola");
etiqueta.setText("Hola "+caja.getText());
}
};
boton.addActionListener(accion);
}
}

EVENTOS DEL TECLADO (KeyListener):


package com.programadornovato.proy1;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;

public class Ventana extends JFrame{


JPanel contenedor;
JButton boton;
JLabel etiqueta;
JTextField caja;
JTextArea areaTexto;
public Ventana(){
contenedor=new JPanel();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
this.getContentPane().add(this.contenedor);
this.contenedor.setLayout(null);
//accionBoton();
//accionRaton();
accionTeclado();
}
protected void accionTeclado(){
caja =new JTextField();
contenedor.add(caja);
caja.setBounds(10, 10, 400, 30);
areaTexto =new JTextArea();
contenedor.add(areaTexto);
areaTexto.setBounds(10, 50, 400, 200);
KeyListener l=new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
//areaTexto.append("keyTyped\n");
}
@Override
public void keyPressed(KeyEvent e) {
//areaTexto.append("keyPressed\n");
}
@Override
public void keyReleased(KeyEvent e) {
//areaTexto.append("keyReleased\n");
if(e.getKeyChar()=='*'){
areaTexto.append("Presionaste el asterico\n");
}
if(e.getKeyChar()=='\n'){
areaTexto.append("Presionaste enter\n");
}
if(e.getKeyChar()==' '){
areaTexto.append("Presionaste espacio\n");
}
}
};
caja.addKeyListener(l);
}

VALIDAR NUMERO:
package com.programadornovato.proy1;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;

public class Ventana extends JFrame{


JPanel contenedor;
JButton boton;
JLabel etiqueta;
JTextField caja;
JTextArea areaTexto;
public Ventana(){
contenedor=new JPanel();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
this.getContentPane().add(this.contenedor);
this.contenedor.setLayout(null);
//accionBoton();
//accionRaton();
//accionTeclado();
validarNumeros();
}
protected void validarNumeros(){
caja =new JTextField();
contenedor.add(caja);
caja.setBounds(10, 10, 400, 30);
areaTexto =new JTextArea();
contenedor.add(areaTexto);
areaTexto.setBounds(10, 50, 400, 200);
KeyListener l=new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if(esNumero(caja.getText())==true){
areaTexto.append("Si es numero\n");
}else{
areaTexto.append("No humano, esto no es un numero\n");
}
}
};
caja.addKeyListener(l);
}
public boolean esNumero(String texto){
boolean resultado;
try {
Integer.parseInt(texto);
resultado=true;
} catch (Exception e) {
resultado=false;
}
return resultado;
}

VALIDAR CORREO:
package com.programadornovato.proy1;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;

public class Ventana extends JFrame{


JPanel contenedor;
JButton boton;
JLabel etiqueta;
JTextField caja;
JTextArea areaTexto;
public Ventana(){
contenedor=new JPanel();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(300, 300, 500, 500);
this.setLocationRelativeTo(null);
this.getContentPane().add(this.contenedor);
this.contenedor.setLayout(null);
//accionBoton();
//accionRaton();
//accionTeclado();
//validarNumeros();
validarCorreo();
}
protected void validarCorreo(){
caja =new JTextField();
contenedor.add(caja);
caja.setBounds(10, 10, 400, 30);
areaTexto =new JTextArea();
contenedor.add(areaTexto);
areaTexto.setBounds(10, 50, 400, 200);
KeyListener l=new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar()=='\n'){
if(esCorreo(caja.getText())==true){
areaTexto.append("Si humano esto es un correo\n");
}
else{
areaTexto.append("No humano estupido esto NO!! es un correo\n");
}
}
}
};
caja.addKeyListener(l);
}
public boolean esCorreo(String correo){
Pattern patroncito = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-
9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
Matcher comparar=patroncito.matcher(correo);
return comparar.find();
}
}

CREAR UNA INTERFAZ GRÁFICA con


netbeans GUI:
ESTE CODIGO ES PARA METER EN EL BOTON

if( nombre.getText().isEmpty()==false ){
saludo.setText("Hola "+nombre.getText());
}else{
JOptionPane.showMessageDialog(null,"Humano ingresa un nombre");
}
CONECTAR TABLA(JTable)
con mysql:
ESTO SE HACE EN pom.xml

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.formulario</groupId>
<artifactId>Formulario</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

<exec.mainClass>com.mycompany.formulario.Formulario</exec.main
Class>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql.conector.java</artifactId>
<version>8.0.15</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

You might also like