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

lunes, 17 de diciembre de 2018

Graficando red neuronal (perceptrón).


Desde Netbeans en modo diseño se añaden los componentes siguiendo esta estructura:

-----------------------------------------------------------------
 

. JFrame (title: "Graficando perceptrón")

  . jPanel1 (aqui se graficará la red neuronal)

  . jToolBar1 (barra de opciones)
    . jLabel1 (texto: "Estructura")
    . jTextField1 (texto: "2,4,4,1")
    . jButton1 (texto: "Graficar")
    . jButton2 (texto: "Limpiar")


-----------------------------------------------------------------



Código 1 (Muro.java):

package centrar;

public class Muro extends javax.swing.JFrame {

   public Muro() {
      initComponents();
      this.setLocationRelativeTo(null);
   }
    
   private void initComponents() { ... } // <- código generado automáticament por Netbeans

   private void jButtonGraficarActionPerformed(java.awt.event.ActionEvent evt) {
      Dibujar t = new Dibujar(jPanel1.getGraphics(), jPanel1.getWidth(), jPanel1.getHeight(), jTextField1.getText());
   }                                              

   private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {
      this.jPanel1.repaint();
   }                                             

   public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            new Muro().setVisible(true);
         }
      });
   }
                
   private javax.swing.JButton jButtonGraficar;
   private javax.swing.JButton jButtonLimpiar;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JPanel jPanel1;
   private javax.swing.JToolBar.Separator jSeparator1;
   private javax.swing.JToolBar.Separator jSeparator2;
   private javax.swing.JTextField jTextField1;
   private javax.swing.JToolBar jToolBar1;       

}



Código 2 (Dibujar.java):

package centrar;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.List;

public class Dibujar {

   Graphics g;
   Graphics2D g2;

   public Dibujar(Graphics g, int width, int height, String estruct) {

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

      // tipos grosores pinceles
      Stroke stroke02 = new BasicStroke(0.2f);
      Stroke stroke04 = new BasicStroke(0.4f);
      g2.setStroke(stroke02);

      // añadir datos estructura perceptrón
      List<Integer> estructura = new ArrayList<>();
      for (String aux1 : estruct.split(",")) {
         estructura.add(Integer.parseInt(aux1));
      }

      int maxX = estructura.size();
      int maxY = maximo(estructura);

      int nParticionesX = maxX + 2; // se suma 2 para margen  superior e inferior
      int nParticionesY = maxY + 2; // se suma 2 para margen  superior e inferior

      int uX = width / nParticionesX;
      int uY = height / nParticionesY;

      float uSeparadorX = (nParticionesX - estructura.size()) / 2f;
      float uSeparadorY;

      int posIniX = (int) Math.round(uX * uSeparadorX);
      int posIniY;

      int[][][] recopilador = new int[maxX][maxY][2]; // k, x, y

      // capa 0: pre-logical posiciones
      for (int x = 0; x < estructura.size(); x++) {
         for (int y = 0; y < estructura.get(x); y++) {
            uSeparadorY = (nParticionesY - estructura.get(x)) / 2f;
            posIniY = (int) Math.round(uY * uSeparadorY);
            recopilador[x][y][0] = (posIniX + (int) uX * x) + (int) (uX / 2);
            recopilador[x][y][1] = (posIniY + (int) uY * y) + (int) (uY / 2);
         }
      }

      // capa 1: graficar neuronas
      int radio = (int) Math.round(uY / 2f);
      for (int x = 0; x < estructura.size(); x++) {
         for (int y = 0; y < estructura.get(x); y++) {
            centrarCirculo(g2, recopilador[x][y][0], recopilador[x][y][1], radio);
         }
      }

      // capa 2: graficar enlaces
      int x1, y1, x2, y2;
      g2.setColor(Color.DARK_GRAY);
      g2.setStroke(stroke04);
      for (int x = 0; x < estructura.size() - 1; x++) {
         for (int y = 0; y < estructura.get(x); y++) {
            for (int k = 0; k < estructura.get(x + 1); k++) {
               x1 = recopilador[x][y][0];
               y1 = recopilador[x][y][1];
               x2 = recopilador[x + 1][k][0];
               y2 = recopilador[x + 1][k][1];
               g2.drawLine(x1, y1, x2, y2);
            }
         }
      }

   }

   private void centrarCirculo(Graphics g2, int x, int y, int r) {
      x = x - (r / 2);
      y = y - (r / 2);
      g2.fillOval(x, y, r, r);
   }

   /* Busca número mayor del listado de la estructura
   * Utilizado para acomodar la gráfica al tamaño de la ventana
    */

   private int maximo(List<Integer> estructura) {
      int max = 0;
      for (int i = 0; i < estructura.size(); i++) {
         if (estructura.get(i) >= max) {
            max = estructura.get(i);
         }
      }
      return max;
   }

}



Resultado:






sábado, 8 de diciembre de 2018

Graficando tablero de ajedrez.


Desde Netbeans y en modo diseño se agrega un jFrame con la opción marcada "Grid Layout" y en propiedades activamos el check [v] undecorated. Se añade luego un jPanel que servirá de lienzo para graficar el tablero.
Para las figuras he instalado una fuente gratuita llamada "Chess Cases".



Código1 (Tabla.java):

package ajedrez;

public class Tabla extends javax.swing.JFrame {

   public Tabla() {
      initComponents();
      this.setBounds(0, 0, 512, 512);
      this.setLocationRelativeTo(null);
      this.jPanel1.setBounds(0, 0, 512, 512);
      this.jPanel1.setBackground(new java.awt.Color(190, 190, 190));
   }

   private void initComponents() { ... } // Código generado automáticamente por Netbeans.                     

   private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {                                    
      Dibujar t = new Dibujar(jPanel1.getGraphics(), this.jPanel1.getWidth());
   }                                   

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


Código2 (Dibujar.java):

package ajedrez;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;

public class Dibujar {

   Rectangle rect = new Rectangle();

   public Dibujar(Graphics g, int xy) {

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

      // Crea tablero
      int casillas = 8;
      int radio = xy / casillas;

      for (int j = 0; j < casillas; j++) {
         for (int i = 0; i < casillas; i++) {
            if ((j % 2) != 0) {
               g2.fillRect(2 * radio * i, radio * j, radio, radio);
            }
            if ((i % 2 != 0)) {
               g2.fillRect(radio * i, 2 * radio * j, radio, radio);
            }
         }
      }

      // Remarcar contorno
      Stroke pincel = new BasicStroke(2f);
      g2.setColor(Color.BLACK);
      g2.setStroke(pincel);
      g2.drawRect(0, 0, xy - 1, xy - 1);

      // Piezas
      Font font = new Font("Chess Cases", Font.TRUETYPE_FONT, 46);
      String piezas = "tmvwlvmt";


      for (int i = 0; i < casillas; i++) {

         // Inserción piezas negras
         g.setColor(Color.BLACK);
         rect.setBounds(radio * i, 0, radio, radio);
         centrarTexto(g, piezas.charAt(i) + "", rect, font);
         rect.setBounds(radio * i, radio, radio, radio);
         centrarTexto(g, "o", rect, font);

         // Inserción piezas blancas
         g.setColor(Color.WHITE);
         rect.setBounds(radio * i, radio * 7, radio, radio);
         centrarTexto(g, piezas.charAt(i) + "", rect, font);
         rect.setBounds(radio * i, radio * 6, radio, radio);
         centrarTexto(g, "o", rect, font);

      }

   }

   private void centrarTexto(Graphics g, String texto, Rectangle r, Font f) {
      FontMetrics medir = g.getFontMetrics(f);
      int x = r.x + (r.width - medir.stringWidth(texto)) / 2;
      int y = r.y + ((r.height - medir.getHeight()) / 2) + medir.getAscent();
      g.setFont(f);
      g.drawString(texto, x, y);
   }

}


Resultado:





viernes, 7 de diciembre de 2018

Graficando rosco del "Pasapalabra" (beta)


Desde Netbeans y en modo diseño se agrega un jFrame con la opción marcada "Grid Layout" y en propiedades activamos el check [v] undecorated. Se añade luego un jPanel, que servirá de lienzo para graficar. Algoritmo claramente mejorable de ahí que lo he puesto versión beta.


Código1 (Muro.java):

package pasapalabra;

public class Muro extends javax.swing.JFrame {
  
   public Muro() {
      initComponents();
      this.setBounds(0, 0, 512, 512);
      this.jPanel1.setBounds(0, 0, 512, 512);
      this.setLocationRelativeTo(null);
      this.repaint();
   }
                     
   private void initComponents() { ... }// Código generado automáticamente por Netbeans                      

   private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {                                    
      double grados = 0;
      Dibujar t = new Dibujar(jPanel1.getGraphics(), this.jPanel1.getWidth() / 2, this.jPanel1.getHeight() / 2, grados);
      Instrucciones(t);
   }                                   
  
   public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(() -> {
         new Muro().setVisible(true);
      });
   }
                  
   private javax.swing.JPanel jPanel1;         

   // Instrucciones tipo tortuga que dibuja
   private void Instrucciones(Dibujar t) {
      int n = 25;
      String letras = "GFEDCBAZYXVUTSRQPOÑNMLJIH";
      double x0, y0, r, grado;
     
      r = jPanel1.getWidth() / 2.5f;
     
      x0 = jPanel1.getWidth() / 2;
      y0 = jPanel1.getHeight() / 2;

      // Ángulo en radianes (importante)
      grado = (2 * Math.PI) / n;

      // Dibuja rosco pasapalabra
      t.gira(0);
      for (int i = 0; i < n; i++) {
         t.avanza(r);
         t.figura(letras.charAt(i));
         t.salta(x0, y0);
         t.gira(grado);
      }
   }
  
}


Código2 (Dibujar.java):

package pasapalabra;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;

public class Dibujar {

   double x, y, angulo;
   Graphics g;
   Graphics2D g2;
   Rectangle rect = new Rectangle();

   public Dibujar(Graphics g, double x, double y, double angulo) {
      this.x = x;
      this.y = y;
      this.angulo = angulo;
      this.g = g;

      g2 = (Graphics2D) g;
      // Filtro "antialiasing"
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
   }

   public void gira(double angulo) {
      this.angulo += angulo;
   }

   public void figura(char letra) {
      int r = 45; // Radio
      double x2 = x - (r / 2);
      double y2 = y - (r / 2);
      g.setColor(Color.BLUE);
      g.fillOval((int) x2, (int) y2, r, r);
      g.setColor(Color.WHITE);
      rect.setBounds((int) x2, (int) y2, r, r);
      centrarTexto(g, "" + letra, rect, new Font("", Font.BOLD, 26));
   }

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

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

   private void centrarTexto(Graphics g, String texto, Rectangle r, Font f) {
      FontMetrics medir = g.getFontMetrics(f);
      int x = r.x + (r.width - medir.stringWidth(texto)) / 2;
      int y = r.y + ((r.height - medir.getHeight()) / 2) + medir.getAscent();
      g.setFont(f);
      g.drawString(texto, x, y);
   }

}


Resultado:




jueves, 6 de diciembre de 2018

Graficando triángulo de pascal (beta)


Desde Netbeans y en modo diseño se agrega un jFrame con la opción marcada "Grid Layout". Se añade luego un jPanel, que servirá de lienzo para graficar. Algoritmo claramente mejorable de ahí que lo he puesto versión beta.


Código1 (Muro.java):

package triangulopascal_2d;

public class Muro extends javax.swing.JFrame {

   public Muro() {
      this.setUndecorated(true);
      initComponents();
      this.setBounds(0, 0, 513, 513);
      this.jPanel1.setBounds(0, 0, 512, 512);
      this.setLocationRelativeTo(null); // Centrar pantalla  
      this.repaint();
   }
                        
   private void initComponents() { ... }         

   private void formMouseClicked(java.awt.event.MouseEvent evt) {                                 
      TrianguloPascal.Dibujar(jPanel1.getGraphics(), this.jPanel1.getWidth());
   }                                

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

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


Código2 (TrianguloPascal.java):


package triangulopascal_2d;

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

public class TrianguloPascal {

   public static void Dibujar(Graphics g, float xy) {

      Graphics2D g2 = (Graphics2D) g;

      // Inicialización variables
      int u = (int) xy / 32;
      int a = 1, b = 29, c = 29;
      int[] d1 = triangulo();
      int indice = 118;

      // Dibuja pirámide de bloques
      while (a <= b) {
         for (int i = a; i <= b; i = i + 2) {
            g2.setColor(Color.BLUE);
            g.fillRect(i * u + 1, c * u + 1, 2 * u - 1, 2 * u - 1);
            g2.setColor(Color.WHITE);
            if (indice >= 0) {
               g.drawString(String.format("%1$5s", d1[indice]), i * u, c * u + 20);
            } else {
               g.drawString(String.format("%1$5s", d1[0]), i * u, c * u + 20);
            }
            indice--;
         }
         a++;
         b--;
         c = c - 2;
      }

   }

   private static int[] triangulo() {

      int[] d1 = new int[119];
      int[][] d2 = new int[16][16];
      d2[1][1] = 1;
     
      int indice = 0;
      for (int j = 2; j < 16; j++) {
         for (int i = 1; i < 16; i++) {
            d2[j][i] = d2[j - 1][i - 1] + d2[j - 1][i];
            if (d2[j][i] != 0) {
               d1[indice] = d2[j][i];
               indice++;
            }
         }
      }

      d1[0] = 1;
      return d1;

   }

}


Resultado:







Con la tecnología de Blogger.