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, 24 de diciembre de 2022

 Dibujar fractal de Mandelbrot

Un fractal de Mandelbrot es una imagen matemática que se crea a partir de una fórmula iterativa y se representa gráficamente en un plano complejo. Cada punto del plano se asigna un color en función de la cantidad de iteraciones que se necesitan para que el valor del número complejo alcance un cierto umbral.


Código java (AI_MandelbrotG.java):

package ai_mandelbrotg;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AI_MandelbrotG extends JPanel {

    public static int WIDTH = 480;
    public static int HEIGHT = 300;
    public static final int MAX_ITERATIONS = 64;

    @Override
    public void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);

        for (int x = 0; x < WIDTH; x++) {
            for (int y = 0; y < HEIGHT; y++) {

                // Calcula el valor de c para el punto (x, y)
                double cReal = (x - WIDTH / 2) * 4.0 / WIDTH;
                double cImag = (y - HEIGHT / 2) * 4.0 / WIDTH;

                // Calcula el valor de z para el punto (x, y)
                double zReal = 0;
                double zImag = 0;

                // Itera hasta encontrar el valor de z para el punto (x, y)
                int iterations = 0;
                while (zReal * zReal + zImag * zImag < 4 && iterations < MAX_ITERATIONS) {
                    double zRealTemp = zReal * zReal - zImag * zImag + cReal;
                    zImag = 2 * zReal * zImag + cImag;
                    zReal = zRealTemp;
                    iterations++;
                }

                // Establece el color para el punto (x, y) en función del número de iteraciones
                int colorValue = 255 * iterations / MAX_ITERATIONS;
                graphics.setColor(new Color(colorValue, colorValue, colorValue));
                graphics.drawLine(x, y, x, y);
            }
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Fractal de Mandelbrot");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        AI_MandelbrotG panel = new AI_MandelbrotG();
        panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

}


Resultado:



viernes, 23 de diciembre de 2022

Crear curva Bézier. Uso de método curveTo de GeneralPath.

Un ejemplo de cómo utilizar el método curveTo de GeneralPath para crear una curva Bézier.
 

Código (Bezier.java): 

package bezier;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Bezier extends JPanel {

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setStroke(new BasicStroke(4.0f));

        int ancho = getWidth();
        int alto = getHeight();
        int x1 = ancho / 4;
        int y1 = alto / 4;
        int x2 = 3 * ancho / 4;
        int y2 = alto / 4;
        int x3 = ancho / 4;
        int y3 = 3 * alto / 4;
        int x4 = 3 * ancho / 4;
        int y4 = 3 * alto / 4;
        GeneralPath path = new GeneralPath();
        path.moveTo(x1, y1);
        path.curveTo(x2, y2, x3, y3, x4, y4);
        g2d.setColor(Color.BLUE);
        g2d.draw(path);
    }

    public static void main(String[] args) {
        JFrame ventana = new JFrame("Curva Bézier");
        ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ventana.add(new
Bezier());
        ventana.setSize(256, 256);
        ventana.setVisible(true);
    }
}


Resultado:



jueves, 27 de octubre de 2022

Mezlar, ordenar, rotar e invertir un listado. Uso "Collections".

Código (EjemploColecciones.java):

package ejemplocolecciones;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class EjemploColecciones {

    public static void main(String[] args) {
        List<Integer> cuadrante = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        //mostrar
        System.out.println("lista inicial:\n" + cuadrante);
        //mezclar
        Collections.shuffle(cuadrante);
        System.out.println("\nmezclar:\n" + cuadrante);
        //ordenar
        Collections.sort(cuadrante);
        System.out.println("\nordenar\n" + cuadrante);
        //rotar hacia la derecha
        Collections.rotate(cuadrante, 1);
        System.out.println("\ndesplazar hacia la derecha:\n" + cuadrante);
        //rotar hacia la izquierda
        Collections.rotate(cuadrante, -1);
        System.out.println("\ndesplazar hacia la izquierda:\n" + cuadrante);
        //invertir
        Collections.reverse(cuadrante);
        System.out.println("\ninvertir:\n" + cuadrante);
    }

}


Resultado:

run:
lista inicial:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

mezclar:
[7, 9, 8, 6, 1, 5, 4, 2, 3]

ordenar
[1, 2, 3, 4, 5, 6, 7, 8, 9]

desplazar hacia la derecha:
[9, 1, 2, 3, 4, 5, 6, 7, 8]

desplazar hacia la izquierda:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

invertir:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
BUILD SUCCESSFUL (total time: 0 seconds)

Rotar elementos de una lista. Uso de "Collections.rotate".

El siguiente algoritmo desplaza una posición los elementos de una lista.


Código (ListaRotar.java):

package listarotar;

import java.util.List;
import java.util.Arrays;
import java.util.Collections;

public class ListaRotar {

    public static void main(String[] args) {
        List<Integer> cuadrante = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        for (int i = 0; i < 9; i++) {
            Collections.rotate(cuadrante, 1);
            System.out.println(cuadrante);
        }
    }

}


Resultado:

run:
[9, 1, 2, 3, 4, 5, 6, 7, 8]
[8, 9, 1, 2, 3, 4, 5, 6, 7]
[7, 8, 9, 1, 2, 3, 4, 5, 6]
[6, 7, 8, 9, 1, 2, 3, 4, 5]
[5, 6, 7, 8, 9, 1, 2, 3, 4]
[4, 5, 6, 7, 8, 9, 1, 2, 3]
[3, 4, 5, 6, 7, 8, 9, 1, 2]
[2, 3, 4, 5, 6, 7, 8, 9, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
BUILD SUCCESSFUL (total time: 0 seconds)

domingo, 23 de octubre de 2022

Cola circular. Uso de Queue.

Una cola circular es una estructura de datos que almacena elementos en una lista (en este caso LinkedList) y que permite acceder a los datos por uno de los dos extremos de la lista. Un elemento se inserta en la cola (parte final) y se suprime/elimina por la parte frontal.


 

Código (colas.java):

package colas;

import java.util.LinkedList;
import java.util.Queue;

public class Colas {

    public static void main(String[] args) {
        Queue<Integer> cola = new LinkedList<>();
        llenar(cola);
        desplazar(cola);
    }

    //llenar cola
    private static void llenar(Queue<Integer> cola) {
        for (int i = 1; i < 10; i++) {
            cola.add(i);
        }
    }

    //correr una posición <-
    private static void desplazar(Queue<Integer> cola) {
        mostrar(cola);
        for (int i = 1; i < 9; i++) {
            cola.add(cola.poll());
            mostrar(cola);
        }
    }

    private static void mostrar(Queue<Integer>
cola) {
        System.out.println(
cola);
    }

}


Resultado:

run:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9, 1]
[3, 4, 5, 6, 7, 8, 9, 1, 2]
[4, 5, 6, 7, 8, 9, 1, 2, 3]
[5, 6, 7, 8, 9, 1, 2, 3, 4]
[6, 7, 8, 9, 1, 2, 3, 4, 5]
[7, 8, 9, 1, 2, 3, 4, 5, 6]
[8, 9, 1, 2, 3, 4, 5, 6, 7]
[9, 1, 2, 3, 4, 5, 6, 7, 8]
BUILD SUCCESSFUL (total time: 0 seconds)

domingo, 16 de octubre de 2022

Mezclar elementos de una lista. Uso de "Collections.shuffle".

Código (GenSudoku.java):

package gensudoku;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class GenSudoku {

    public static void main(String[] args) {
        List<Integer> valores = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        System.out.println("valores no mezclados: " + valores);
        Collections.shuffle(valores);
        System.out.println("valores si mezclados: " + valores);
    }

}


Resultado:

valores no mezclados: [1, 2, 3, 4, 5, 6, 7, 8, 9]
valores si mezclados: [3, 9, 2, 8, 4, 5, 7, 1, 6]

sábado, 15 de octubre de 2022

Arrastrar un gráfico con el mouse dentro de jFrame.

Código Java (ArrastrarGrafico.java):

package arrastrargrafico;

import javax.swing.WindowConstants;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;

public class ArrastrarGrafico extends Canvas implements MouseMotionListener {

    private int xRectangulo = 0;
    private int yRectangulo = 0;
    private final int anchoRectangulo = 64;
    private final int altoRectangulo = 64;
    private int xAnteriorRaton;
    private int yAnteriorRaton;
    private boolean arrastrando = false;

    public static void main(String[] args) {
        JFrame v = new JFrame("Arrastrar Grafico");
        ArrastrarGrafico c = new ArrastrarGrafico();
        v.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        v.getContentPane().add(c);
        v.setVisible(true);
        v.pack();
    }

    public ArrastrarGrafico() {
        addMouseMotionListener(this);
    }

    private boolean estaDentro(MouseEvent e) {
        return (e.getX() > xRectangulo)
                && (e.getX() < (xRectangulo + anchoRectangulo))
                && (e.getY() > yRectangulo)
                && (e.getY() < (yRectangulo + altoRectangulo));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(512, 512);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.BLUE);
        g.fillRect(xRectangulo, yRectangulo, anchoRectangulo, altoRectangulo);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (!arrastrando) {
            if (estaDentro(e)) {
                xAnteriorRaton = e.getX();
                yAnteriorRaton = e.getY();
                arrastrando = true;
            }
        } else {
            xRectangulo = (xRectangulo + e.getX()) - xAnteriorRaton;
            yRectangulo = (yRectangulo + e.getY()) - yAnteriorRaton;
            xAnteriorRaton = e.getX();
            yAnteriorRaton = e.getY();
            repaint();
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        arrastrando = false;
    }

}


Resultado:


miércoles, 12 de octubre de 2022

Conversor a código Braille. Uso de HashMap con matriz.

Braille es un sistema de lectura y escritura táctil pensado para personas ciegas.
Un carácter en Braile se puede representar por una matriz de puntos de tamaño 2x3.
Este algoritmo lo que hace es convertir una frase a código en Braille.


Código1 (CodigoBraille.java):

package codigobraille;

public class CodigoBraille {
    public static void main(String[] args) {
        Braille m = new Braille();
        m.braille();
    }
}


Código2 (Braille.java):

package codigobraille;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
import javax.imageio.ImageIO;

public class Braille {

    HashMap<String, Boolean[][]> tablaCodigoBraille = new HashMap<>();

    public void braille() {
        tablaCodigoBraille = getTablaM();
        System.out.println("Escriba un mensaje a convertir a braille:");
        Scanner input = new Scanner(System.in);
        String mensaje = input.nextLine();

        //tamaño lienzo
        int res_x = 1024;
        int res_y = 1024;

        BufferedImage imagen = new BufferedImage(res_x, res_y, BufferedImage.TYPE_INT_RGB);
        Lienzo.Dibujar((Graphics2D) imagen.getGraphics(), res_x, res_y, mensaje, tablaCodigoBraille);
        try {
            ImageIO.write(imagen, "png", new File("Braille.png"));
        } catch (IOException e) {
        }
    }

    private static HashMap<String, Boolean[][]> getTablaM() {

        //tabla código braille español +- (2x3)
        HashMap<String, Boolean[][]> par = new HashMap<>();
        par.put(" ", new Boolean[][]{
            {false, false},
            {false, false},
            {false, false}});
        par.put("A", new Boolean[][]{
            {true, false},
            {false, false},
            {false, false}});
        par.put("B", new Boolean[][]{
            {true, false},
            {true, false},
            {false, false}});
        par.put("C", new Boolean[][]{
            {true, true},
            {false, false},
            {false, false}});
        par.put("D", new Boolean[][]{
            {true, true},
            {false, true},
            {false, false}});
        par.put("E", new Boolean[][]{
            {true, false},
            {false, true},
            {false, false}});
        par.put("F", new Boolean[][]{
            {true, true},
            {true, false},
            {false, false}});
        par.put("G", new Boolean[][]{
            {true, true},
            {true, true},
            {false, false}});
        par.put("H", new Boolean[][]{
            {true, false},
            {true, true},
            {false, false}});
        par.put("I", new Boolean[][]{
            {false, true},
            {true, false},
            {false, false}});
        par.put("J", new Boolean[][]{
            {false, true},
            {true, true},
            {false, false}});
        par.put("K", new Boolean[][]{
            {true, false},
            {false, false},
            {true, false}});
        par.put("L", new Boolean[][]{
            {true, false},
            {true, false},
            {true, false}});
        par.put("M", new Boolean[][]{
            {true, true},
            {false, false},
            {true, false}});
        par.put("N", new Boolean[][]{
            {true, true},
            {false, true},
            {true, false}});
        par.put("O", new Boolean[][]{
            {true, false},
            {false, true},
            {true, false}});
        par.put("P", new Boolean[][]{
            {true, true},
            {true, false},
            {true, false}});
        par.put("Q", new Boolean[][]{
            {true, true},
            {true, true},
            {true, false}});
        par.put("R", new Boolean[][]{
            {true, false},
            {true, true},
            {true, false}});
        par.put("S", new Boolean[][]{
            {false, true},
            {true, false},
            {true, false}});
        par.put("T", new Boolean[][]{
            {false, true},
            {true, true},
            {true, false}});
        par.put("U", new Boolean[][]{
            {true, false},
            {false, false},
            {true, true}});
        par.put("V", new Boolean[][]{
            {true, false},
            {true, false},
            {true, true}});
        par.put("W", new Boolean[][]{
            {false, true},
            {true, true},
            {false, true}});
        par.put("X", new Boolean[][]{
            {true, true},
            {false, false},
            {true, true}});
        par.put("Y", new Boolean[][]{
            {true, true},
            {false, true},
            {true, true}});
        par.put("Z", new Boolean[][]{
            {true, false},
            {false, true},
            {true, true}});
        par.put("&", new Boolean[][]{
            {true, true},
            {true, false},
            {true, true}});
        par.put(".", new Boolean[][]{
            {false, false},
            {false, false},
            {true, false}});
        par.put(",", new Boolean[][]{
            {false, false},
            {true, false},
            {false, false}});
        par.put("?", new Boolean[][]{
            {false, false},
            {true, false},
            {false, true}});
        par.put(":", new Boolean[][]{
            {false, false},
            {true, true},
            {false, false}});
        par.put(";", new Boolean[][]{
            {false, false},
            {true, false},
            {true, false}});
        par.put("!", new Boolean[][]{
            {false, false},
            {true, true},
            {true, false}});
        par.put("\"", new Boolean[][]{
            {false, false},
            {true, false},
            {true, true}});
        par.put("(", new Boolean[][]{
            {true, false},
            {true, false},
            {false, true}});
        par.put(")", new Boolean[][]{
            {false, true},
            {false, true},
            {true, false}});
        par.put("-", new Boolean[][]{
            {false, false},
            {false, false},
            {true, true}});
        par.put("*", new Boolean[][]{
            {false, false},
            {false, true},
            {true, false}});
        return par;
    }
}


Código3 (Lienzo.java):

package codigobraille;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.HashMap;

class Lienzo {

    static void Dibujar(Graphics2D g, int x, int y, String msg, HashMap<String, Boolean[][]> map) {

        //tamaño bloque
        int tCuadroX = 16;
        int tCuadroY = 16;
        int t = 10; //tamaño punto

        Boolean tmp[][] = new Boolean[3][2];

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

        //fondo blanco
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, x, y);

        //dibujar escritura Braille
        g.setColor(Color.black);
        int horizontal = 1, vertical = 3, limit = 0;
        for (int k = 0; k < msg.length(); k++) {
            //dibujar el caracter en braile
            tmp = map.get("" + msg.toUpperCase().charAt(k));
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 3; j++) {
                    if (tmp[j][i]) {
                        g.fillOval(tCuadroX * (i + horizontal), tCuadroY * (j + vertical), t, t);
                    }
                }
            }            
            //ha llegado al limite de linea?
            if (limit++ >= 21) {
                horizontal = 1;
                vertical += 6;
                limit = 0;
            } else {
                horizontal += 3;
            }
        }
    }

}


Resultado:

run:
Escriba un mensaje a convertir a braille:
En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no hace mucho tiempo que vivia un hidalgo de los de lanza en astillero, adarga antigua, rocin flaco y galgo corredor. (DON QUIJOTE DE LA MANCHA)
BUILD SUCCESSFUL (total time: 3 seconds)


Con la tecnología de Blogger.