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, 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)


sábado, 8 de octubre de 2022

Emitir notas musicales en formato sintetizado (midi).

Código (PruebaSonidoMidi.java):

package pruebasonidomidi;

import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Synthesizer;

public class PruebaSonidoMidi {

    public static void main(String[] args) {

        try {
            Synthesizer synth = MidiSystem.getSynthesizer();
            synth.open();
            MidiChannel[] channels = synth.getChannels();
            for (int i = 5; i < 100; i++) {
                channels[0].noteOn(i, 50);
                Thread.sleep(200);
            }
            synth.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}


Con la tecnología de Blogger.