Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.

Archivo del blog

miércoles, 19 de marzo de 2014

Gráficos en 2D. Curva de Hilbert.

Se crea un nuevo proyecto en Netbeans y en vista de diseño se agrega un jButton y un jPanel.


Codigo 1 (Principal.java):

package CurvaHilbert;

public class Principal extends javax.swing.JFrame {

    int x, y, depth, size;

    public Principal() {
        initComponents();
        this.setLocationRelativeTo(null);// Centrar pantalla
    }

                            
    private void initComponents() { ... }// Codigo generado automaticamente                       

    private void jButtonIniciarActionPerformed(java.awt.event.ActionEvent evt){           

        Dibujo.Dibujar(
                jPanel1.getGraphics(),
                x = jPanel1.getWidth() / 2,
                y = jPanel1.getHeight() / 2,
                depth = 4,
                size = jPanel1.getHeight() / 2);

    }                                             

    public static void main(String args[]) {

       java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton jButtonIniciar;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                  
}



Codigo 2 (Dibujo.java):

package CurvaHilbert;

import java.awt.Graphics;

public class Dibujo {
   
    public static void Dibujar(Graphics g, int x, int y, int n, int size) {
        if (n == 0) return;
        int x0 = x - size / 2;
        int x1 = x + size / 2;
        int y0 = y - size / 2;
        int y1 = y + size / 2;
        g.drawLine(x0, y0, x0, y1);
        g.drawLine(x1, y0, x1, y1);
        g.drawLine(x0, y, x1, y);
        Dibujar(g, x0, y0, n - 1, size / 2);
        Dibujar(g, x0, y1, n - 1, size / 2);
        Dibujar(g, x1, y0, n - 1, size / 2);
        Dibujar(g, x1, y1, n - 1, size / 2);

    }

}



Resultado:


lunes, 10 de marzo de 2014

Gráficos en 2D. Creación de un Fractal (Árbol).

Se crea un nuevo proyecto en Netbeans y en vista de diseño se agrega un jButton y un jPanel.


Codigo (FractalFree.java):

package FractalTree;

public class FractalTree extends javax.swing.JFrame {

    public FractalTree() {
        initComponents();
        this.setLocationRelativeTo(null); //Centrar pantalla       
    }

                            
    private void initComponents() { ... } //Codigo generado automáticamente                       

    private void jButtonIniciarActionPerformed(java.awt.event.ActionEvent evt) {

        Dibujo.Dibujar(
                jPanel1.getGraphics(),
                jPanel1.getWidth() / 2,
                jPanel1.getHeight(),
                -90, 9);

    }                                             

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FractalTree().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton jButtonIniciar;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                  
}



Codigo 2 (Dibujo.java):

package FractalTree;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class Dibujo {
    public static void Dibujar(Graphics g, int x1, int y1, double angle, int depth) {
        if (depth == 0) return;
        Graphics2D g2 = (Graphics2D) g;
        g.setColor(Color.BLUE);
        g2.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
//Filtro antialiasing             
       
        int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 5.0);
        int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 5.0);

        g2.drawLine(x1, y1, x2, y2);
        Dibujar(g2, x2, y2, angle - 20, depth - 1);
        Dibujar(g2, x2, y2, angle + 20, depth - 1);

    }
}



Resultado:


Gráficos en 2D. Imagenes aleatorias.

Este ejemplo consiste en que al pulsar un jButton se crea una imagen aleatoria cualquiera. Normalmente las imagenes que aparecen no tienen sentido, pero de hecho si Java tuviera una aleatoriedad absoluta, tarde o temprano acabarias apareciendo en una de estas imagenes. Y esque en la aleatoriedad esta el TODO. Por poner un ejemplo, para calcular la probabilidad de que aparezca "La Mona Lisa":

P(Mona Lisa) = 1 / {(Numero de Colores RBG)^(Tamaño jPanel)}
P(Mona Lisa) = 1 / { (255 x 255 x 255)^(375 x 250) }
P(Mona Lisa) = 3.75 x 10^(-676840)


Para empezar se crea un nuevo proyecto y en modo de diseño se agrega un jButton y un jPanel.


Codigo 1 (Principal.java):

package imagenesAleatorias;

public class Principal extends javax.swing.JFrame {
    public Principal() {
        initComponents();
        this.setLocationRelativeTo(null); //Centrar pantalla      
    }
                            
    private void initComponents() { ... }//Codigo generado automáticamente                       

    private void jButtonIniciarActionPerformed(java.awt.event.ActionEvent evt){

         Dibujo.Dibujar(jPanel1.getGraphics(),
         jPanel1.getWidth(),
         jPanel1.getHeight());
    }                                            

    public static void main(String args[]) {     
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                   
    private javax.swing.JButton jButtonIniciar;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                 
}



Codigo 2 (Dibujo.java): 

package imagenesAleatorias;

import java.awt.Color;
import java.awt.Graphics;

public class Dibujo {
    public static void Dibujar(Graphics g, int width, int height) {
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                g.setColor(new Color(
                        (float) Math.random(),
                        (float) Math.random(),
                        (float) Math.random()));
                g.fillRect(i, j, 1, 1);
//dibuja pixel

            }
        }
    }
}



Resultado:



Gráficos en 2D. Camino Aleatorio (Random Walks).

Se crea un nuevo proyecto en Netbeans y en vista de diseño se agrega un jButton y un jPanel.


Codigo 1 (Principal.java):

package graficos1;

public class Principal extends javax.swing.JFrame {

    public Principal() {
        initComponents();
        this.setLocationRelativeTo(null); //Centrar pantalla
    }

    @SuppressWarnings("unchecked")

    private void initComponents() {...}      

    private void jButtonIniciarMouseClicked(java.awt.event.MouseEvent evt) {        

        Dibujo.Dibujar(jPanel1.getGraphics(), jPanel1.getWidth(), jPanel1.getHeight());
    }                                          

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton jButtonIniciar;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                  
}

 

Codigo 2 (Dibujo.java):

package graficos1;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class Dibujo {

    public static void Dibujar(Graphics g, int width, int height) {


        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.BLUE);

        int pasos = 25000, pos;
        int w = width / 2;
        int h = height / 2;
       
        for (int i = 0; i < pasos; i++) {
            pos = (int) Math.floor(Math.random() * 8 + 1);
            switch (pos) {
                case 1:
                    w--;
                    h++;
                    break;
                case 2:
                    h++;
                    break;
                case 3:
                    w++;
                    h++;
                    break;
                case 4:
                    w++;
                    break;
                case 5:
                    w++;
                    h--;
                    break;
                case 6:
                    h--;
                    break;
                case 7:
                    w--;
                    h--;
                    break;
                case 8:
                    w--;
                    break;
            }
           
            //Dibuja un punto
            g2.fillOval(w, h, 1, 1);

            //Control laterales
            w = (w > width) ? 1 : w;
            w = (w < 1) ? width : w;
            h = (h > height) ? 1 : h;
            h = (h < 1) ? height : h;

        }
    }

}



Resultado:












Con la tecnología de Blogger.