Link LogUna manera de perder el tiempo…
Posts Tagged ‘Java’
Reloj en Java
with 7 comments
Bueno, después de mucho mucho tiempo, aquí traigo de nuevo otro programa en Java, este programa solo es un simple reloj analógico (ya saben, esos que tienen manecillas).
Bueno, acá el reloj resultante:
Reloj en Java
Acá el código:
view source
print ? 001 import java.awt.*; 002 import java.awt.event.*; 003 import java.awt.image.*;
004 import javax.swing.*; 005 import javax.swing.event.*; 006 import java.util.*; 007 008 public class RelojProyecto extends JFrame{ 009 public static void main(String[] args) { 010 RelojProyecto app = new RelojProyecto(); 011 app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 012 }
013 014 Reloj Cara;
015 016 public RelojProyecto() { 017 super( "Reloj Proyecto" ); 018 setVisible( true ); 019 setResizable( false ); 020 Container content = this.getContentPane(); 021 content.setLayout(new BorderLayout()); 022 Cara = new Reloj(); 023 content.add(Cara, BorderLayout.CENTER); 024 this.pack();
025 026 Cara.start(); 027 } 028 }
029 030 class Reloj extends JPanel { 031 032 private int horas; 033 private int minutos; 034 private int segundos; 035 036 private static final int espacio = 10; 037 private static final float dosPi = (float)(2.0 * Math.PI); 038 private static final float tresPi = (float)(3.0 * Math.PI); 039 private static final float rad = (float)(Math.PI / 30.0); 040 041 private int tamano; 042 private int xCentro; 043 private int yCentro; 044 private BufferedImage muestra; 045 private javax.swing.Timer t; 046 047 public Reloj() { 048 this.setPreferredSize(new Dimension(300,300)); 049 t = new javax.swing.Timer(1000, 050 new ActionListener() { 051 public void actionPerformed(ActionEvent e) {
052 update(); 053 } 054 }); 055 }
056 057 public void update() { 058 this.repaint(); 059 }
060 061 public void start() { 062 t.start(); 063 } 064 public void stop() { 065 t.stop(); 066 } 067 public void paintComponent(Graphics g) { 068 super.paintComponent(g); 069 Graphics2D g2 = (Graphics2D)g;
070 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
071 072 int ancho = getWidth(); 073 int alto = getHeight(); 074 tamano = ((ancho < alto) ? ancho : alto) - 2*espacio; 075 xCentro = tamano/2 + espacio; 076 yCentro = tamano/2 + espacio; 077 078 if (muestra == null079 || muestra.getWidth() != ancho 080 || muestra.getHeight() != alto) {
081 082 muestra = (BufferedImage)(this.createImage(ancho, alto)); 083 Graphics2D gc = muestra.createGraphics(); 084 gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 085 RenderingHints.VALUE_ANTIALIAS_ON); 086 caraReloj(gc); 087 }
088 089 Calendar now = Calendar.getInstance(); 090 horas = now.get(Calendar.HOUR); 091 minutos = now.get(Calendar.MINUTE); 092 segundos = now.get(Calendar.SECOND);
093 094 g2.drawImage(muestra, null, 0, 0);
095 096 Manecillas(g); 097 }
098
099 private void caraReloj(Graphics g) { 100 101 g.setColor(new Color(209, 234, 255)); 102 g.fillOval(espacio, espacio, tamano, tamano); 103 g.setColor(Color.black); 104 g.drawOval(espacio, espacio, tamano, tamano);
105 106 for (int seg = 0; seg<60; seg++) { 107 int inicio; 108 if (seg%5 == 0) { 109 inicio = tamano/2-10; 110 } else { 111 inicio = tamano/2-5; 112 } 113 diseno(g, xCentro, yCentro, rad*seg, inicio , tamano/2); 114 } 115 }
116 117 private void Manecillas(Graphics g) { 118 int radioSegundero = tamano/2; 119 int radioMinutero = radioSegundero * 3/4; 120 int radioHora = radioSegundero/2; 121 122 float fsegundos = segundos; 123 float anguloSegundero = tresPi - (rad * fsegundos);
124 diseno(g, xCentro, yCentro, anguloSegundero, 0, radioSegundero);
125 126 float fminutos = (float)(minutos + fsegundos/60.0); 127 float anguloMinutero = tresPi - (rad * fminutos); 128 diseno(g, xCentro, yCentro, anguloMinutero, 0, radioMinutero);
129 130 float fhours = (float)(horas + fminutos/60.0); 131 float anguloHora = tresPi - (5 * rad * fhours); 132 diseno(g, xCentro, yCentro, anguloHora, 0, radioHora);
133 134 Font font = new Font("Arial", Font.BOLD, 16); 135 g.setFont(font); 136 g.drawString( "12", 140, 40 ); 137 g.drawString( "1", 205, 55 ); 138 g.drawString( "2", 245, 100 ); 139 g.drawString( "3", 265, 155 ); 140 g.drawString( "4", 245, 210 ); 141 g.drawString( "5", 205, 255 ); 142 g.drawString( "6", 145, 270 ); 143 g.drawString( "7", 90, 255 ); 144 g.drawString( "8", 45, 210 ); 145 g.drawString( "9", 25, 155 );
146 g.drawString( "10", 45, 100 ); 147 g.drawString( "11", 80, 55 ); 148 Font font1 = new Font("Arial", Font.BOLD, 12); 149 g.setFont(font1); 150 g.drawString( "RELOJ", 130, 80 ); 151 g.drawString( "QUARTZ", 125, 220 ); 152 }
153
154 private void diseno(Graphics g, int x, int y, double angulo, int minRadius, int maxRadius) {
155 float sine = (float)Math.sin(angulo); 156 float cosine = (float)Math.cos(angulo); 157 158 int dxmin = (int)(minRadius * sine); 159 int dymin = (int)(minRadius * cosine); 160 161 int dxmax = (int)(maxRadius * sine); 162 int dymax = (int)(maxRadius * cosine); 163 g.drawLine( x+dxmin, y+dymin, x+dxmax, y+dymax); 164 } 165 }
Written by Link X
May 18, 2009 at 9:09 pm
Posted in Java
Tagged with Java, Programación
Código
with one comment
Para las personas que llegan aquí buscando código de algún tema en especifico (sobretodo código de Java), les informo que el código publicado en este blog funciona, solo que si lo copian directamente del navegador al editor puede tener problemas al copiarse, sobretodo con las comillas(“” ya que se copian como ¨¨), por lo que es recomendable escribir el código directamente al editor y después compilarlo, así no habrá problemas.
No creo que haya problemas, después de todo ya esta todo resuelto y solo es necesario que lo copien.
Aunque si hay algún problema o duda me lo pueden decir.
Written by Link X
November 27, 2008 at 1:14 am
Posted in General
Tagged with codigo, Copiar, Java, Programación
Java AWT
without comments
Aquí esta un ejemplo muy pero muy sencillo de gráficos en Java.
El programa en si no hace nada, solo se muestra lo que se necesita para crear una ventana con botones (que no hacen nada…).
view source
print ? 01 import java.awt.*; 02 public class ejemplo{ 03 public static void main( String args[] ){ 04
05 Button boton = new Button( "Soy un botón y el de abajo no hace nada" );
06 Button boton2 = new Button( "El botón de arriba no hace nada" ); 07 08 Frame vent = new Frame( "Ejemplo Java AWT" ); 09 vent.setLayout(new FlowLayout()); 10 vent.add( boton ); 11 vent.add( boton2 ); 12 vent.setSize( 300, 150 ); 13 vent.setVisible( true ); 14 15 vent.addWindowListener(new Conclusion()); 16 } 17 }
Creo que todo el código se entiende, lo único que se puede llegar a no entender es la ultima linea (vent.addWindowsListener…), esta es una linea muy importante, ya que sin ella no cierra la ventana.
Written by Link X
June 18, 2008 at 11:13 pm
Posted in Java
Tagged with awt, graficos, Java, Programación
Colas en Java
with 10 comments
Ya puse unos ejemplos de listas y pilas, pero todavía hace falta el ejemplo de colas (no de esas, pero no estaría mal poner unos buenos ejemplos…).
Bueno, lo que hace este programa, es mostrar un menú para que el usuario seleccione lo que desee hacer, si insertar, retirar o mostrar la cola (de Java…).
view source
print ? 01 import java.util.*; 02 public class Cola { 03 public static void main( String args[] ){ 04 Scanner leer = new Scanner(System.in); 05 06 colagenerica obj = new colagenerica(); 07 08 int op; 09 int num; 10 11 do{ 12 menu(); 13 op = leer.nextInt();
14 15 switch(op){ 16 case 1: 17 System.out.println( "Numero a insertar" ); 18 num = leer.nextInt(); 19 if(obj.inscola(num)){
20 System.out.println( "fre"+obj.fre+"fin"+obj.fin+"aux"+obj.max );
21 System.out.println( "El numero "+num+" se
inserto en la cola ["+obj.dret+"]" ); 22 System.out.println(); 23 } 24 else{ 25 System.out.println( "Cola llena" ); 26 } 27 break; 28 case 2: 29 if(obj.retcola()){ 30 System.out.println( "El dato retirado fue:
"+obj.dret ); 31 } 32 else{ 33 System.out.println( "Cola vacia" ); 34 } 35 break; 36 case 3: 37 if(obj.fre==-1 && obj.fin==-1){ 38 System.out.println( "Cola vacia" ); 39 } 40 else{ 41 System.out.println( "Estado de la cola:" ); 42 for(int i=obj.fre; i<=obj.fin; i++){ 43 System.out.print(obj.c[i]+" \t"); 44 } 45 break; 46 } 47 } 48 } 49 while(op != 4); 50 }
51 52 public static void menu(){ 53 System.out.println( "\t Menu para colas \n" ); 54 System.out.println( "1.- Insertar" ); 55 System.out.println( "2.- Retirar" ); 56 System.out.println( "3.- Estado" ); 57 System.out.println( "4.- Fin" ); 58 System.out.println( "\n Selecciona" ); 59 } 60 }
El programa usa métodos de la clase colagenerica, que puedes ver haciendo clic en mas
Read the rest of this entry »
Written by Link X
June 5, 2008 at 7:19 pm
Posted in Java
Tagged with colas, Java, Programación
Listas en Java (LinkedList)
with 2 comments
De nuevo las listas, pero esta va vez con LinkedList, lo que permite que se agreguen o eliminen elementos en la lista al inicio o al final.
view source
print ? 01 import java.util.*; 02 public class ListaLigada { 03 04 public static void main (String args[]) { 05 Scanner leer = new Scanner(System.in); 06 07 int num; 08 int op; 09 10 LinkedList lista = new LinkedList(); 11 do{ 12 System.out.println( "\t Menú \t" ); 13 System.out.println( "Operaciones con listas" ); 14 System.out.println( "1.- Insertar al principio" ); 15 System.out.println( "2.- Insertar al final" ); 16 System.out.println( "3.- Borrar al principio" ); 17 System.out.println( "4.- Borrar al final" ); 18 System.out.println( "5.- Mostrar la lista" ); 19 System.out.println( "6.- Borrar toda la lista" ); 20 System.out.println( "7.- Salir" ); 21 System.out.println( "\n" ); 22 System.out.println( "Elija la operación que desee" ); 23 24 op = leer.nextInt();
25 26 switch(op){ 27 case 1: 28 System.out.println( "Inserte numero" ); 29 num = leer.nextInt(); 30 lista.addFirst(num); 31 break; 32 case 2: 33 System.out.println( "Inserte numero" ); 34 num = leer.nextInt(); 35 lista.addLast(num); 36 break; 37 case 3:
38 System.out.println( "Se borrara el primer nodo" );
39 lista.removeFirst(); 40 break; 41 case 4:
42 System.out.println( "Se borrara el nodo final" ); 43 lista.removeLast(); 44 break; 45 case 5: 46 System.out.println( "La lista es la siguiente" ); 47 List lista2 = new ArrayList(lista); 48 Iterator it = lista2.iterator(); 49 while (it.hasNext()){ 50 System.out.println(it.next()+""); 51 } 52 break; 53 case 6:
54 System.out.println( "Se borraran todos los
elementos de la lista" ); 55 lista.clear(); 56 break; 57 case 7: 58 System.out.println( "Al rato" ); 59 break; 60 } 61 }
62 63 while( op != 7 ); 64 } 65 }
Written by Link X
June 1, 2008 at 10:08 pm
Posted in Java
Tagged with Java, LinkedList, listas, Programación
Listas en Java
with one comment
Bueno, este programa hace lo mismo que el anterior, solo que esta hecho de la manera “tradicional”, es decir, sin usar ArrayList o LinkedList. Se podría decir que la lista esta hecha de forma manual.
Clase Nodo
view source
print ?
1 public class NLista1{ 2 String nom; 3 int calif1; 4 int calif2; 5 int calif3; 6 double prom; 7 8 NLista1 liga; 9 }
Programa
view source
print ? 01 import java.util.*; 02 public class Lista1 { 03 04 public static void main (String args[]) { 05 Scanner leer = new Scanner(System.in); 06 07 NLista1 inicio = null; 08 NLista1 fin = null; 09 NLista1 nuevo = null; 10 NLista1 aux = null;
11 12 int op; 13 14 do{ 15 nuevo = new NLista1(); 16 System.out.println( "Ingrese el nombre del estudiante" ); 17 nuevo.nom = leer.next(); 18 System.out.println( "Ingrese la primer calificación" ); 19 nuevo.calif1 = leer.nextInt(); 20 System.out.println( "Ingrese la segunda calificación" ); 21 nuevo.calif2 = leer.nextInt(); 22 System.out.println( "Ingrese la tercer calificación" ); 23 nuevo.calif3 = leer.nextInt();
24 25 if(inicio == null){ 26 inicio = nuevo; 27 nuevo.liga = null; 28 } 29 else{ 30 fin.liga = nuevo; 31 nuevo.liga = null; 32 }
33
34 fin = nuevo; 35 Promedio(nuevo);
36 37 System.out.println( "¿Desea ingresar otro estudiante?" ); 38 System.out.println( "1.-Si \t 2.-No" ); 39 op = leer.nextInt(); 40 }
41 42 while(op != 2);
43 44 aux = inicio;
45 46 while(aux != null){ 47 System.out.println( "Nombre \t Promedio" ); 48 System.out.println( aux.nom + "\t" + aux.prom ); 49 aux = aux.liga; 50 }
51 52 }
53 54 public static double Promedio(NLista1 nuevo){ 55 int suma = nuevo.calif1 + nuevo.calif2 + nuevo.calif3; 56 nuevo.prom = suma/3; 57 return nuevo.prom; 58 } 59 }
Written by Link X
May 31, 2008 at 2:01 am
Posted in Java
Tagged with Java, listas, Programación
Listas en Java (ArrayList)
with 19 comments
Aquí esta un ejemplo de listas en Java utilizando ArrayList:
Lo que hace este programa, es que pide el nombre del alumno y tres calificaciones para luego calcular su promedio. Se puede agregar cualquier cantidad de elementos a la lista.
view source
print ? 1 public class NodoLista4{ 2 String nom; 3 int calif1; 4 int calif2; 5 int calif3; 6 }
view source
print ? 01 import java.util.*; 02 public class ListaAlumnos{ 03 04 static double prom; 05 public static void main( String args[] ){ 06 Scanner leer = new Scanner(System.in); 07 08 NodoLista4 nodo = new NodoLista4(); 09 int op; 10 11 ArrayList lista = new ArrayList(); 12 do{ 13 System.out.println( "Ingrese el nombre del alumno:" ); 14 nodo.nom = leer.next(); 15 System.out.println( "Ingrese la primera calificación:" ); 16 nodo.calif1 = leer.nextInt(); 17 System.out.println( "Ingrese la segunda calificación:" ); 18 nodo.calif2 = leer.nextInt(); 19 System.out.println( "Ingrese la tercera calificación:" ); 20 nodo.calif3 = leer.nextInt();
21 22 lista.add("Nombre del alumno:\n"+nodo.nom); 23 lista.add("Calificación 1:\n"+nodo.calif1); 24 lista.add("Calificación 2:\n"+nodo.calif2); 25 lista.add("Calificación 3\n"+nodo.calif3);
26 27 promedio(nodo.calif1, nodo.calif2, nodo.calif3);
28 29 lista.add("Su promedio es:\n"+prom);
30 31 System.out.println( "¿Desea ingresar otro alumno?" ); 32 System.out.println( "1.-Si\t 2.-No" ); 33 op = leer.nextInt(); 34 } 35 while(op != 2); 36 List lista2 = new ArrayList(lista); 37 Iterator it = lista2.iterator();
38 while (it.hasNext()){ 39 System.out.println(it.next()+""); 40 } 41 }
42 43 private static double promedio(int calif1, int calif2, int calif3){ 44 int suma = calif1 + calif2 + calif3; 45 prom = suma/3; 46 return prom; 47 } 48 }
P.D.: No es necesario hacer el NodoLista4, esas variables se pueden crear en el programa, pero me acostumbre a hacer eso…
Written by Link X
May 27, 2008 at 12:28 pm
Posted in Java
Tagged with arraylist, Java, listas, Programación
Java Infijo a Posfijo
with 2 comments
Bueno, ya conociendo el algoritmo, se puede hacer en Java:
view source
print ? 01 class converpostultima{ 02 public static void main (String args[]) 03 {
04 05 String expr = new String(""); 06 String exprpost = new String(""); 07 char ch; 08 int max; 09 System.out.print("Dame la Expresion en Infijo: "); 10 expr =Leer.dato(); 11 max=expr.length(); 12 operapilaschar obj1 = new operapilaschar(max); 13 System.out.println(); 14 System.out.println(); 15 System.out.println("La Expresion en Postfijo es :");
16 obj1.push('('); // inserta '(' a la PILA 17 expr+=')'; // inserta ')' al final de Q
18 for (int i=0;i=precedencia(ch) && obj1.pila[obj1.tope]!='('))
19 { 20 obj1.pop(); 21 exprpost+=obj1.dret; 22 } 23 obj1.push(ch); 24 break; 25 case ')': while (obj1.pila[obj1.tope] != '(') 26 { 27 obj1.pop(); 28 exprpost+=obj1.dret; 29 } 30 obj1.pop(); 31 break; 32 default : exprpost+=ch; 33 }
34 35 } 36 while (!(obj1.pila_Vacia(obj1.tope))) 37 { 38 obj1.pop(); 39 if (obj1.dret!= '(') 40 exprpost+=obj1.dret; 41 } 42 System.out.println(exprpost); 43 }
44 45 public static int precedencia(char ch) 46 { 47 int aux = 0; 48 switch (ch) 49 { 50 case '^' : aux = 4; 51 break; 52 case '*' : case '/' : aux = 3; 53 break; 54 case '+' : case '-' : aux = 2; 55 break; 56 case '(' : aux = 1; 57 break; 58 } 59 return aux; 60 } 61 }