Foro de elhacker.net

Programación => Java => Mensaje iniciado por: Meta en 6 Marzo 2015, 06:25 am



Título: Encontrar motivos de fallos sobre código Java.
Publicado por: Meta en 6 Marzo 2015, 06:25 am
Hola:

Tengo un código medio hecho en el cual no se el motivo de los fallos. Se trata de encender y apagar un Led con Netbeans 8 en mi caso y Arduino.

Código
  1. import gnu.io.CommPortIdentifier;
  2. import gnu.io.SerialPort;
  3. import java.io.OutputStream;
  4. import java.util.Enumeration;
  5. import javax.swing.JOptionPane;
  6.  
  7. /*
  8.  * To change this license header, choose License Headers in Project Properties.
  9.  * To change this template file, choose Tools | Templates
  10.  * and open the template in the editor.
  11.  */
  12.  
  13. /**
  14.  *
  15.  * @author Meta
  16.  */
  17. public class JAVADUINO_JFrame extends javax.swing.JFrame {
  18.  
  19.    /**
  20.      * Creates new form JAVADUINO_JFrame
  21.      */
  22.  
  23.    private static final String L8ON = "Led_8_ON";
  24.    private static final String L8OFF = "Led_8_OFF";
  25.  
  26.    // Variables de conexión.
  27.    private final OutputStream output = null;
  28.    SerialPort serialPort;
  29.    private final String PUERTO = "COM4";
  30.  
  31.    private static final int TIMEOUT = 2000;
  32.  
  33.    private static final int DATA_RATE = 115200;
  34.  
  35.    public JAVADUINO_JFrame() {
  36.        initComponents();
  37.        inicializarConexion();
  38.    }
  39.  
  40.    public final void inicializarConexion(){
  41.        CommPortIdentifier puertoID = null;
  42.        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  43.  
  44.        while(puertoEnum.hasMoreElements()){
  45.            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  46.            if (PUERTO.equals(actualPuertoID.getName())){
  47.                puertoID = actualPuertoID;
  48.                break;
  49.            }
  50.        }
  51.    }
  52.  
  53.    if (puertoID == null){
  54.    mostrarError("No se puede conectar al puerto.");
  55.    System.exit(ERROR);
  56. }
  57.  
  58.    try{
  59.        serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  60.        // Parámetros puerto serie.
  61.        serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
  62.        output = serialPort.getOutputStream();
  63. }
  64.    catch (Exception e){
  65.    mostrarError(e.getMessage());
  66.    System.exit(ERROR);
  67. }
  68.  
  69.    private void enviarDatos(String datos){
  70.        try{
  71.            output.write(datos.getBytes());
  72.        }
  73.        catch(Exception e){
  74.            mostrarError("ERROR");
  75.            System.exit(ERROR);
  76.        }
  77.    }
  78.  
  79.    public void mostrarError(String mensaje){
  80.        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
  81.  
  82.    }
  83.    /**
  84.      * This method is called from within the constructor to initialize the form.
  85.      * WARNING: Do NOT modify this code. The content of this method is always
  86.      * regenerated by the Form Editor.
  87.      */
  88.    @SuppressWarnings("unchecked")
  89.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  90.    private void initComponents() {
  91.  
  92.        jButton1 = new javax.swing.JButton();
  93.        jButton2 = new javax.swing.JButton();
  94.  
  95.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  96.  
  97.        jButton1.setText("ON");
  98.  
  99.        jButton2.setText("OFF");
  100.  
  101.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  102.        getContentPane().setLayout(layout);
  103.        layout.setHorizontalGroup(
  104.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  105.            .addGroup(layout.createSequentialGroup()
  106.                .addGap(21, 21, 21)
  107.                .addComponent(jButton1)
  108.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
  109.                .addComponent(jButton2)
  110.                .addGap(45, 45, 45))
  111.        );
  112.        layout.setVerticalGroup(
  113.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  114.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  115.                .addContainerGap(250, Short.MAX_VALUE)
  116.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  117.                    .addComponent(jButton1)
  118.                    .addComponent(jButton2))
  119.                .addGap(27, 27, 27))
  120.        );
  121.  
  122.        pack();
  123.    }// </editor-fold>                        
  124.  
  125.    /**
  126.      * @param args the command line arguments
  127.      */
  128.    public static void main(String args[]) {
  129.        /* Set the Nimbus look and feel */
  130.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  131.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  132.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  133.          */
  134.        try {
  135.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  136.                if ("Nimbus".equals(info.getName())) {
  137.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  138.                    break;
  139.                }
  140.            }
  141.        } catch (ClassNotFoundException ex) {
  142.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  143.        } catch (InstantiationException ex) {
  144.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  145.        } catch (IllegalAccessException ex) {
  146.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  147.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  148.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  149.        }
  150.        //</editor-fold>
  151.  
  152.        /* Create and display the form */
  153.        java.awt.EventQueue.invokeLater(new Runnable() {
  154.            public void run() {
  155.                new JAVADUINO_JFrame().setVisible(true);
  156.            }
  157.        });
  158.    }
  159.  
  160.    // Variables declaration - do not modify                    
  161.    private javax.swing.JButton jButton1;
  162.    private javax.swing.JButton jButton2;
  163.    // End of variables declaration                  
  164.  
  165.    private void mostrarError(String no_se_puede_conectar_al_puerto) {
  166.        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  167.    }
  168. }
  169.  

Todavía no he programado los botones, hay que acabar con los fallos primero. Los mensajes que me dan son estos.
Citar
run:
java.lang.ClassFormatError: Duplicate field name&signature in class file JAVADUINO_JFrame
   at java.lang.ClassLoader.defineClass1(Native Method)
   at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
   at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
   at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
   at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
   at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
   at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
   at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

He segudio los tutoriales hasta el minuto 37':30" de este vídeo.
https://www.youtube.com/watch?v=4Hr_LZ62SdY

¿Alguna idea?

Saludos.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Usuario Invitado en 6 Marzo 2015, 13:00 pm
ClassFormatException se lanza cuando el compilador no ha podido identificar dicho código como una clase. Pueden ser múltiples los problemas, desde interfaces mal implementadas, o clases mal anotadas, etc.

Me causa asombro, que NetBeans no te corrija esto:

Código
  1. public final void inicializarConexion(){
  2. CommPortIdentifier puertoID = null;
  3. Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  4.  
  5. while(puertoEnum.hasMoreElements()){
  6. CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  7. if (PUERTO.equals(actualPuertoID.getName())){
  8. puertoID = actualPuertoID;
  9. break;
  10.  
  11. }
  12.  
  13. }
  14.  
  15. } // aquí has cerrado el método inicilizarConexion(), por lo no podría
  16. // si quiera compilar el if debajo ni el try-catch.
  17. if (puertoID == null){
  18. mostrarError("No se puede conectar al puerto.");
  19. System.exit(ERROR);
  20. }

En la línea 15 como puedes ver has cerrado el método inicializarConexión. Toda instrucción a no ser que sea una declaración o un bloque estático, debe hacerse dentro de un método o constructor. No se pueden escribir instrucciones sin algún método que los englobe. Por eso, me parece raro en sobremanera que NetBeans no te marque en rojo lo que hay debajo del método.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Meta en 6 Marzo 2015, 14:23 pm
Hola:

Código
  1. /*
  2. import gnu.io.CommPortIdentifier;
  3. import gnu.io.SerialPort;
  4. import java.io.OutputStream;
  5. import java.util.Enumeration;
  6. import javax.swing.JOptionPane;
  7. */
  8.  
  9. import java.io.OutputStream;
  10. import gnu.io.CommPortIdentifier;
  11. import gnu.io.SerialPort;
  12. import java.util.Enumeration;
  13. import javax.swing.JOptionPane;
  14.  
  15. /*
  16.  * To change this license header, choose License Headers in Project Properties.
  17.  * To change this template file, choose Tools | Templates
  18.  * and open the template in the editor.
  19.  */
  20.  
  21. /**
  22.  *
  23.  * @author Meta
  24.  */
  25. public class JAVADUINO_JFrame extends javax.swing.JFrame {
  26.  
  27.    /**
  28.      * Creates new form JAVADUINO_JFrame
  29.      */
  30.  
  31.    private static final String L8ON = "Led_8_ON";
  32.    private static final String L8OFF = "Led_8_OFF";
  33.  
  34.    // Variables de conexión.
  35.    private final OutputStream output = null;
  36.    SerialPort serialPort;
  37.    private final String PUERTO = "COM4";
  38.  
  39.    private static final int TIMEOUT = 2000;
  40.  
  41.    private static final int DATA_RATE = 115200;
  42.  
  43.    public JAVADUINO_JFrame() {
  44.        initComponents();
  45.        inicializarConexion();
  46.    }
  47.  
  48.    public final void inicializarConexion(){
  49.        CommPortIdentifier puertoID = null;
  50.        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  51.  
  52.        while(puertoEnum.hasMoreElements()){
  53.            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  54.            if (PUERTO.equals(actualPuertoID.getName())){
  55.                puertoID = actualPuertoID;
  56.                break;
  57.            }
  58.        }
  59.  
  60.            if (puertoID == null){
  61.    mostrarError("No se puede conectar al puerto.");
  62.    System.exit(ERROR);
  63. }
  64.  
  65.    try{
  66.        serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  67.        // Parámetros puerto serie.
  68.        serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
  69.        output = serialPort.getOutputStream();
  70. }
  71.    catch (Exception e){
  72.    mostrarError(e.getMessage());
  73.    System.exit(ERROR);
  74. }
  75.    }
  76.  
  77.  
  78.    private void enviarDatos(String datos){
  79.        try{
  80.            output.write(datos.getBytes());
  81.        }
  82.        catch(Exception e){
  83.            mostrarError("ERROR");
  84.            System.exit(ERROR);
  85.        }
  86.    }
  87.  
  88.    public void mostrarError(String mensaje){
  89.        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
  90.  
  91.    }
  92.    /**
  93.      * This method is called from within the constructor to initialize the form.
  94.      * WARNING: Do NOT modify this code. The content of this method is always
  95.      * regenerated by the Form Editor.
  96.      */
  97.    @SuppressWarnings("unchecked")
  98.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  99.    private void initComponents() {
  100.  
  101.        jButton1 = new javax.swing.JButton();
  102.        jButton2 = new javax.swing.JButton();
  103.  
  104.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  105.  
  106.        jButton1.setText("ON");
  107.  
  108.        jButton2.setText("OFF");
  109.  
  110.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  111.        getContentPane().setLayout(layout);
  112.        layout.setHorizontalGroup(
  113.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  114.            .addGroup(layout.createSequentialGroup()
  115.                .addGap(21, 21, 21)
  116.                .addComponent(jButton1)
  117.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
  118.                .addComponent(jButton2)
  119.                .addGap(45, 45, 45))
  120.        );
  121.        layout.setVerticalGroup(
  122.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  123.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  124.                .addContainerGap(250, Short.MAX_VALUE)
  125.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  126.                    .addComponent(jButton1)
  127.                    .addComponent(jButton2))
  128.                .addGap(27, 27, 27))
  129.        );
  130.  
  131.        pack();
  132.    }// </editor-fold>                        
  133.  
  134.    /**
  135.      * @param args the command line arguments
  136.      */
  137.    public static void main(String args[]) {
  138.        /* Set the Nimbus look and feel */
  139.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  140.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  141.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  142.          */
  143.        try {
  144.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  145.                if ("Nimbus".equals(info.getName())) {
  146.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  147.                    break;
  148.                }
  149.            }
  150.        } catch (ClassNotFoundException ex) {
  151.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  152.        } catch (InstantiationException ex) {
  153.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  154.        } catch (IllegalAccessException ex) {
  155.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  156.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  157.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  158.        }
  159.        //</editor-fold>
  160.  
  161.        /* Create and display the form */
  162.        java.awt.EventQueue.invokeLater(new Runnable() {
  163.            public void run() {
  164.                new JAVADUINO_JFrame().setVisible(true);
  165.            }
  166.        });
  167.    }
  168.  
  169.    // Variables declaration - do not modify                    
  170.    private javax.swing.JButton jButton1;
  171.    private javax.swing.JButton jButton2;
  172.    // End of variables declaration                  
  173.  
  174.    private void mostrarError(String no_se_puede_conectar_al_puerto) {
  175.        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  176.    }
  177. }
  178.  

Me sale este error.
Citar
run:
java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Uncompilable source code - method mostrarError(java.lang.String) is already defined in class JAVADUINO_JFrame
   at JAVADUINO_JFrame.<clinit>(JAVADUINO_JFrame.java:174)
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Saludos.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Usuario Invitado en 6 Marzo 2015, 15:48 pm
Aquí está tu error:

Citar
Caused by: java.lang.RuntimeException: Uncompilable source code - method mostrarError(java.lang.String) is already defined in class JAVADUINO_JFrame

Traducido:

Método mostrarError(java.lang.String) está actualmente definido en la clase JAVADUINO_JFrame.

Cuando haces sobrecarga es necesario hacer cualquier de las siguientes cosas:

  • Cambiar el método de retorno.
  • Cambiar orden o tipo de objeto de los parámetros.

Estás redefiniendo el método mostrarError(String msg). Primero muestras el error en un JOptionPane y luego lanzas una excepción con el error.

Asumo que no estás utilizando NetBeans actualmente, porque NetBeans hace inspección en tiempo real y detecta estos errores.


Saludos.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Meta en 6 Marzo 2015, 16:27 pm
Hola:

Uso netbeans 8.0.2 en español.

Mirando el código lo he hecho otra vez desde cero.
Código
  1. import gnu.io.CommPortIdentifier;
  2. import gnu.io.SerialPort;
  3. import java.io.OutputStream;
  4. import java.util.Enumeration;
  5. import javax.swing.JOptionPane;
  6.  
  7. /*
  8.  * To change this license header, choose License Headers in Project Properties.
  9.  * To change this template file, choose Tools | Templates
  10.  * and open the template in the editor.
  11.  */
  12.  
  13. /**
  14.  *
  15.  * @author Meta
  16.  */
  17. public class JAVADUINO_Frame extends javax.swing.JFrame {
  18.  
  19.    /**
  20.      * Creates new form JAVADUINO_Frame
  21.      */
  22.  
  23.    private static final String L8on = "Led_8_ON";
  24.    private static final String L8off = "Led_8_OFF";
  25.  
  26.    // Variables de conexión.
  27.    private OutputStream output = null;
  28.    SerialPort serialPort;
  29.    private final String PUERTO = "COM4";
  30.  
  31.    private static final int TIMEOUT = 2000; // 2 segundos.
  32.  
  33.    private static final int DATA_RATE = 115200; // Baudios.
  34.  
  35.    public JAVADUINO_Frame() {
  36.        initComponents();
  37.        inicializarConexion();
  38.    }
  39.  
  40.    public void inicializarConexion(){
  41.        CommPortIdentifier puertoID = null;
  42.        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  43.  
  44.        while (puertoEnum.hasMoreElements()){
  45.            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  46.            if (PUERTO.equals(actualPuertoID.getName())){
  47.                puertoID = actualPuertoID;
  48.                break;
  49.            }
  50.        }
  51.  
  52.        if (puertoID == null){
  53.            mostrarError("No se puede conectar al puerto");
  54.            System.exit(ERROR);
  55.        }
  56.  
  57.        try{
  58.            serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  59.            // Parámatros puerto serie.
  60.  
  61.            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
  62.  
  63.            output = serialPort.getOutputStream();
  64.        } catch (Exception e){
  65.            mostrarError(e.getMessage());
  66.            System.exit(ERROR);
  67.        }
  68.    }
  69.  
  70.    private void enviarDatos(String datos){
  71.        try{
  72.            output.write(datos.getBytes());
  73.        } catch (Exception e){
  74.            mostrarError("ERROR");
  75.            System.exit(ERROR);
  76.        }
  77.    }
  78.  
  79.    public void mostrarError(String mensaje){
  80.        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);    
  81.    }
  82.    /**
  83.      * This method is called from within the constructor to initialize the form.
  84.      * WARNING: Do NOT modify this code. The content of this method is always
  85.      * regenerated by the Form Editor.
  86.      */
  87.    @SuppressWarnings("unchecked")
  88.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  89.    private void initComponents() {
  90.  
  91.        jButton1 = new javax.swing.JButton();
  92.        jButton2 = new javax.swing.JButton();
  93.  
  94.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  95.  
  96.        jButton1.setText("ON");
  97.  
  98.        jButton2.setText("OFF");
  99.  
  100.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  101.        getContentPane().setLayout(layout);
  102.        layout.setHorizontalGroup(
  103.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  104.            .addGroup(layout.createSequentialGroup()
  105.                .addContainerGap()
  106.                .addComponent(jButton1)
  107.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 99, Short.MAX_VALUE)
  108.                .addComponent(jButton2)
  109.                .addContainerGap())
  110.        );
  111.        layout.setVerticalGroup(
  112.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  113.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  114.                .addContainerGap(92, Short.MAX_VALUE)
  115.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  116.                    .addComponent(jButton1)
  117.                    .addComponent(jButton2))
  118.                .addGap(26, 26, 26))
  119.        );
  120.  
  121.        pack();
  122.    }// </editor-fold>                        
  123.  
  124.    /**
  125.      * @param args the command line arguments
  126.      */
  127.    public static void main(String args[]) {
  128.        /* Set the Nimbus look and feel */
  129.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  130.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  131.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  132.          */
  133.        try {
  134.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  135.                if ("Nimbus".equals(info.getName())) {
  136.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  137.                    break;
  138.                }
  139.            }
  140.        } catch (ClassNotFoundException ex) {
  141.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  142.        } catch (InstantiationException ex) {
  143.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  144.        } catch (IllegalAccessException ex) {
  145.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  146.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  147.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  148.        }
  149.        //</editor-fold>
  150.  
  151.        /* Create and display the form */
  152.        java.awt.EventQueue.invokeLater(new Runnable() {
  153.            public void run() {
  154.                new JAVADUINO_Frame().setVisible(true);
  155.            }
  156.        });
  157.    }
  158.  
  159.    // Variables declaration - do not modify                    
  160.    private javax.swing.JButton jButton1;
  161.    private javax.swing.JButton jButton2;
  162.    // End of variables declaration                  
  163. }
  164.  


Uso Windows 7 de 64 bits.

Me sle este error.
Citar
run:
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
   at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1865)
   at java.lang.Runtime.loadLibrary0(Runtime.java:870)
   at java.lang.System.loadLibrary(System.java:1119)
   at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:83)
   at JAVADUINO_Frame.inicializarConexion(JAVADUINO_Frame.java:43)
   at JAVADUINO_Frame.<init>(JAVADUINO_Frame.java:38)
   at JAVADUINO_Frame$1.run(JAVADUINO_Frame.java:155)
   at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
   at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:749)
   at java.awt.EventQueue.access$500(EventQueue.java:97)
   at java.awt.EventQueue$3.run(EventQueue.java:702)
   at java.awt.EventQueue$3.run(EventQueue.java:696)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
   at java.awt.EventQueue.dispatchEvent(EventQueue.java:719)
   at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
   at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
   at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
   at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
   at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
   at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

El que más me llama la ateción es este:
Citar
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path

Saludos.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Usuario Invitado en 6 Marzo 2015, 16:46 pm
Creo que no está encontrando las dll. Intenta lo siguiente:

  • Click derecho al proyecto -> Properties.
  • Ve hacia Run.
  • En VM arguments escribe la ruta del dll de la siguiente forma:

    Código:
    -Djava.library.path="ruta/hacia/el/dll"

    Si hay más dll escribe un espacio y vuelve a escribir el código anterior, así con todas las dll o .so, etc.

    Corre nuevamente el programa y comentas.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Meta en 6 Marzo 2015, 17:28 pm
Lo puse así:

Citar
-Djava.library.path="C:\Program Files (x86)\Java\jre1.8.0_40\bin"

Me aparece esto:
Citar
run:
java.lang.UnsatisfiedLinkError: C:\Program Files (x86)\Java\jre1.8.0_40\bin\rxtxSerial.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform thrown while loading gnu.io.RXTXCommDriver
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: C:\Program Files (x86)\Java\jre1.8.0_40\bin\rxtxSerial.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform

También puse esto:
Citar
-Djava.library.path="C:\Program Files\Java\jre1.8.0_31\bin\rxtxSerial.dll"

Nombrando la dll y todo pero sigue con elmismo mensaje.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Usuario Invitado en 6 Marzo 2015, 17:45 pm
Si usas Java de 64 bits debes recompilar dicha biblioteca a 64 bits o puedes instalar la JVM de 32 bits.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Meta en 6 Marzo 2015, 17:57 pm
Por lo que veo, mejor usar todo a 32 bits.
 
Lo instalaré todo a 32 bits por si acaso, a lo mejor es más cómodo y rápido.

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

https://netbeans.org/downloads/8.0.1/

Desinstalé todo a 64 bits e instalé todo a 32 bits en Windows de 64 bits a ver que pasa. En este momento estoy descargando la última versión y a 32 bits, luego comento.

Saludos.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Meta en 6 Marzo 2015, 18:56 pm
Ya me ejecuta, lo instaré todo a 32 bits.

https://www.youtube.com/watch?v=JAwCa4Uk6tA

Estoy haciendo un buen tutorial sobre puerto serie con Visual Studio y Java.

(https://social.msdn.microsoft.com/Forums/getfile/616372)

Si quieres te envío en pdf hasta donde he llegado.

Muchísimas gracias por la ayuda.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Usuario Invitado en 6 Marzo 2015, 19:56 pm
Wow, se ve muy bueno ^^, claro envíame el PDF como que lo sigo con el tuto.

Saludos.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Meta en 6 Marzo 2015, 20:25 pm
Hola:

Claro que si, me envías tu correo y te lo paso a PDF, me falta muchos temas por acabar. Java recibir datos de texto que es lo que quiero hacer desde ya, VB 6. y todo referente a la electrónica que aúnno he acabado.

También lo mismo pero en modo consola, hay gente que lo quiere así y con todos los lenguajes. ;)

En otro manual, con Linux y Java y puede hasya con monodevelop C#, cosas así. Repito para que se entienda, me falta esquemas de electrónica que pondré poco a poco y bien explicado y algunos vídeos, por ahora solo tengo este.

g7XPhDL6auA


Mi correo es metacontaARROBAgmail com.

Saludos.


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Usuario Invitado en 6 Marzo 2015, 20:33 pm
Vale, gracias. Creo que te he encontrado en Skype, no se tendrás esa cuenta activa. De todos modos, coordinamos por MP.

Un saludo!


Título: Re: Encontrar motivos de fallos sobre código Java.
Publicado por: Meta en 6 Marzo 2015, 20:41 pm
Te he enviado MP.