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

sábado, 7 de noviembre de 2020

Gráficos en 2D. Diagrama de Voronoi.

Código Java (voronoi.java):


package voronoi;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class Voronoi extends javax.swing.JFrame {
    
    BufferedImage imagen;
    int px[], py[], color[], zonas = 21, size = 350;

    public Voronoi() {
        
        super("Diagrama de Voronoi");
        setBounds(0, 0, size, size);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
                
        imagen = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
        px = new int[zonas];
        py = new int[zonas];
        color = new int[zonas];
        Random rand = new Random();
        for (int i = 0; i < zonas; i++) {
            px[i] = rand.nextInt(size);
            py[i] = rand.nextInt(size);
            color[i] = rand.nextInt(16777215);
        }
        int n;
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                n = 0;
                for (int i = 0; i < zonas; i++) {
                    if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
                        n = i;
                    }
                }
                imagen.setRGB(x, y, color[n]);
            }
        }
    }    
    
    @Override
    public void paint(Graphics g) {
        g.drawImage(imagen, 0, 0, this);
    }

    double distance(int x1, int x2, int y1, int y2) {
        double d;
        d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
        return d;
    }

    public static void main(String[] args) {
        new Voronoi().setVisible(true);
    }

}


Resultado:





domingo, 25 de octubre de 2020

Gráficos en 2D. Diseño 2

Código Java (Design2.java):

package design;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import javax.swing.Timer;

public class Design2 extends javax.swing.JFrame {

    Trazador t;

    public Design2() {
        initComponents();
        this.setLocationRelativeTo(null);

        t = new Trazador(
                jPanel1.getGraphics(),
                jPanel1.getWidth(),
                jPanel1.getHeight(),
                0);

        Timer timer = new Timer(100, (ActionEvent e) -> {
            int a = 0;
            int b = 0;
            t.salta(245, 300);
            while (true) {
                for (int i = 0; i < 4; i++) {
                    t.avanza(80);
                    t.gira(90);
                }
                t.gira(15);
                a++;
                if (a >= 390 / 15) {
                    t.avanza(50);
                    a = 0;
                    b++;
                    if (b >= 12) {
                        break;
                    }
                }
            }
        });
        timer.start();
        timer.setRepeats(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Design 2 - 2020");
        setMinimumSize(new java.awt.Dimension(450, 450));
        setPreferredSize(new java.awt.Dimension(300, 300));
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridLayout(1, 0));

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanel1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 643, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 488, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel1);

        getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>                        

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

    }                                    

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

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

    private static class Trazador {

        double x, y, angulo;
        Graphics g;

        private Trazador(Graphics g, float x, float y, float angulo) {

            this.x = x;
            this.y = y;
            this.angulo = angulo * Math.PI / 180;
            this.g = g;

            Graphics2D g2 = (Graphics2D) g;
            g2.setStroke(new BasicStroke(0.3f));
            g2.setColor(Color.YELLOW);
            g2.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

        }

        public void gira(double angulo) {
            this.angulo += angulo * Math.PI / 180;
        }

        public void avanza(double distancia) {
            double x2 = x + distancia * Math.cos(angulo);
            double y2 = y - distancia * Math.sin(angulo);
            g.drawLine((int) x2, (int) y2, (int) x, (int) y);
            salta(x2, y2);
        }

        public void salta(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
}

Resultado:



Gráficos en 2D. Diseño 1

Código Java (Design1.java):

package design;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import javax.swing.Timer;

public class Design1 extends javax.swing.JFrame {

    Trazador t;

    public Design1() {
        initComponents();
        this.setLocationRelativeTo(null);

        t = new Trazador(
                jPanel1.getGraphics(),
                jPanel1.getWidth() / 2,
                jPanel1.getHeight() / 2,
                0);

        Timer timer = new Timer(100, (ActionEvent e) -> {
            int cont = 0;
            while (true) {
                for (int i = 0; i < 4; i++) {
                    t.avanza(90);
                    t.gira(90);
                }
                t.gira(5);
                cont++;
                if (cont >= 360 / 5) {
                    break;
                }
            }
        });
        timer.start();
        timer.setRepeats(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Design 1 - 2020");
        setMinimumSize(new java.awt.Dimension(300, 300));
        setPreferredSize(new java.awt.Dimension(300, 300));
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridLayout(1, 0));

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanel1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 643, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 488, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel1);

        getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>                        

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

    }                                    

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

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

    private static class Trazador {

        double x, y, angulo;
        Graphics g;

        private Trazador(Graphics g, float x, float y, float angulo) {

            this.x = x;
            this.y = y;
            this.angulo = angulo * Math.PI / 180;
            this.g = g;

            Graphics2D g2 = (Graphics2D) g;
            g2.setStroke(new BasicStroke(1));
            g2.setColor(Color.YELLOW);
            g2.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

        }

        public void gira(double angulo) {
            this.angulo += angulo * Math.PI / 180;
        }

        public void avanza(double distancia) {
            double x2 = x + distancia * Math.cos(angulo);
            double y2 = y - distancia * Math.sin(angulo);
            g.drawLine((int) x2, (int) y2, (int) x, (int) y);
            salta(x2, y2);
        }

        public void salta(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
}

Resultado:



Gráficos en 2D. Diseño 0

Código Java (Principal.java):

package octagono;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import javax.swing.Timer;

public class Principal extends javax.swing.JFrame {

   
Trazador t;

    public Principal() {
        initComponents();
        this.setLocationRelativeTo(null);

        t = new
Trazador(
                jPanel1.getGraphics(),
                jPanel1.getWidth() / 2,
                jPanel1.getHeight() / 2,
                0);

        Timer timer = new Timer(100, (ActionEvent e) -> {
            for (int i = 0; i < 8; i++) {
                t.gira(-45);
                for (int j = 0; j < 8; j++) {
                    t.avanza(45);
                    t.gira(45);
                }
            }
        });
        timer.start();
        timer.setRepeats(false);
    }

    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Octogonal Shape");
        setMinimumSize(new java.awt.Dimension(300, 300));
        setPreferredSize(new java.awt.Dimension(300, 300));
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridLayout());

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 643, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 488, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel1);

        pack();

    }                       


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

    private static class
Trazador {

        double x, y, angulo;
        Graphics g;

        private Trazador(Graphics g, float x, float y, float angulo) {

            this.x = x;
            this.y = y;
            this.angulo = angulo * Math.PI / 180;
            this.g = g;

            Graphics2D g2 = (Graphics2D) g;
            g2.setStroke(new BasicStroke(2)); //Grosor pincel
            g2.setColor(Color.YELLOW); //Color
            g2.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);//Filtro de suavizado

        }

        public void gira(double angulo) {
            this.angulo += angulo * Math.PI / 180;
        }

        public void avanza(double distancia) {
            double x2 = x + distancia * Math.cos(angulo);
            double y2 = y - distancia * Math.sin(angulo);
            g.drawLine((int) x2, (int) y2, (int) x, (int) y);
            salta(x2, y2);
        }

        public void salta(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
}

 

Resultado:



 



sábado, 26 de septiembre de 2020

Sucesión de Fibonacci

La sucesión de Fibonacci comienza con los números 0 y 1 y a partir de estos cada número que les precede es la suma de los dos anteriores.

 

Código Java (Fibonacci.java):


package fibonacci;

public class Fibonacci {

    public static void main(String[] args) {
        int f0 = 0, f1 = 1, tmp;
        do {
            System.out.println(f0);
            tmp = f0 + f1;
            f0 = f1;
            f1 = tmp;
        } while (f0 < 1000);
    }

}


Resultado:

run:
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
BUILD SUCCESSFUL (total time: 0 seconds)


viernes, 12 de junio de 2020

Patrón III: Triángulo.

Código Java (Triangulos.java):

package triangulos;

import java.util.Scanner;

class Triangulos {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Entra tamaño del triángulo: ");
        int n = in.nextInt();
        for (int i = n; i > 0; i--) {
            for (int j = 1; j < i; j++) {
                System.out.print(" ");
            }
            for (int j = i; j <= n; j++) {
                System.out.print("* ");
            }
            System.out.println("");
        }
    }
   
}


Resultado:

run:
Entra tamaño del triangulo: 10
         *
        * *
       * * *
      * * * *
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *
 * * * * * * * * *
* * * * * * * * * *
BUILD SUCCESSFUL (total time: 3 seconds)


sábado, 16 de mayo de 2020

Cuadro binario aleatorio 16x16

Código Java (CuadroBinario.java):

package cuadrobinario;

public class CuadroBinario {

    public static void main(String[] args) {
        int n = 0;
        for (int i = 0; i < 16; i++) {
            for (int j = 0; j < 16; j++) {
                n = (int) (Math.random() * 2);
                System.out.print(String.format("%1$2s", n));
            }
            System.out.println("");
        }
    }

}



Resultado:

run:
 1 0 0 1 0 1 1 1 0 1 1 1 1 0 0 0
 1 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1
 0 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0
 0 1 1 0 0 1 1 1 0 0 1 0 0 0 0 1
 0 1 1 0 0 0 0 1 0 0 0 0 0 1 1 1
 1 1 0 0 0 1 0 1 1 0 1 1 0 0 0 1
 1 0 0 1 0 1 0 0 1 1 1 0 0 0 0 0
 1 1 0 1 0 0 0 1 0 0 0 0 0 1 1 1
 1 1 1 1 0 0 1 0 1 0 0 0 1 1 1 0
 1 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1
 0 0 0 0 0 1 1 0 1 1 1 0 0 1 0 0
 0 1 1 1 0 1 0 0 0 1 1 0 0 1 1 0
 1 0 1 0 1 0 0 0 0 0 0 0 1 0 0 1
 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0
 1 1 0 1 1 1 1 0 0 0 0 0 1 0 1 0
 0 0 0 1 1 0 0 1 1 1 1 0 0 0 1 0
BUILD SUCCESSFUL (total time: 0 seconds)



viernes, 10 de abril de 2020

Patrón II: Cuadrado.

Código Java (Cuadros.java)

package cuadros;

import java.util.Scanner;

public class Cuadros {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Entra tamaño del cuadro: ");
        int n = in.nextInt();       
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print("* ");
            }
            System.out.println("");
        }
    }

}



Resultado:

run:
Entra tamaño del cuadro: 10
* * * * *
* * * * *
* * * * * * * * * *
* * * * *
* * * * *
* * * * * * * * * *  
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * *
BUILD SUCCESSFUL (total time: 2 seconds)

Con la tecnología de Blogger.