elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: AIO elhacker.NET 2021 Compilación herramientas análisis y desinfección malware


  Mostrar Mensajes
Páginas: 1 ... 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 [49] 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 ... 255
481  Programación / Scripting / Re: Ejecutar este código de Python en Visual Studio en: 28 Agosto 2017, 13:12 pm
Lo he intentado y no aparece la plantilla que indica en el enlace que pusiste.
482  Programación / Scripting / Ejecutar este código de Python en Visual Studio en: 27 Agosto 2017, 18:49 pm
Buenas:

Tengo un código de Python y quiero ejecutarlo en Visual Studio. Nunca he tratado de hacer ejecutar un código de Python, a ver si sale.

He instalado los componentes necesario.

Código de Python:
Código
  1. import os, sys, tkFileDialog,Tkinter
  2.  
  3. root = Tkinter.Tk()
  4. root.withdraw()
  5.  
  6. formats = [ ('Roms Super Nintendo SMC','.smc'),('Roms Super Nintendo SFC','.sfc'),('Fichier Bin','.bin'),('Roms Super Nintendo','.smc .sfc .bin') ]
  7.  
  8. input = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=formats,title='Elija el archivo para swapper')
  9. if not input:
  10. print "¡Imposible de abrir el archivo!"
  11. sys.exit()
  12.  
  13. output = tkFileDialog.asksaveasfile(parent=root,mode='wb',filetypes=formats,title='Elija el archivo de salida')
  14. if not output:
  15. print "¡No se puede crear el archivo de salida!"
  16. sys.exit()
  17.  
  18.  
  19. # Lectura del archivo de entrada a un array de bytes
  20. data = bytearray(input.read())
  21.  
  22. # Calculando el tamaño de la habitación en 2 exponentes
  23. expsize = 0
  24. bytesize = len(data)
  25. while bytesize > 1:
  26. expsize += 1
  27. bytesize = bytesize // 2
  28.  
  29. # Unidad de un tamaño adecuado matriz de bytes vacíos
  30. buffer = bytearray()
  31. for i in range(2**expsize): buffer.append(0)
  32.  
  33. # let's do the swap
  34. count = 0
  35. for i in range(len(data)):
  36. addr = (i & 0x7fff) + ((i & 0x008000) << (expsize - 16)) + ((i & 0x010000) >> 1) + ((i & 0x020000) >> 1) + ((i & 0x040000) >> 1) + ((i & 0x080000) >> 1) + ((i & 0x100000) >> 1) + ((i & 0x200000) >> 1)
  37. if addr != i: count += 1
  38. buffer[addr] = data[i]
  39. print "Swapped %s (%s) addresses" % (count, hex(count))
  40.  
  41. # Escribir archivo de salida
  42. output.write(buffer)
  43.  
  44. # Cerrar carpetas de archivos
  45. input.close()
  46. output.close()

Creo el proyecto de Python pero no tengo idea donde hay que darle exactamente con todo lo que tiene.


¿Alguna idea?

Saludos.
483  Programación / Java / Pasar código de NetBeans a Eclipse en: 26 Agosto 2017, 21:51 pm
Hola:
Tengo este código hecho desde NetBeans y quiero adaptarlo a Eclipse. La verdad no sale igual.

NetBeans:
Código
  1. import gnu.io.CommPortIdentifier;
  2. import gnu.io.SerialPort;
  3. import gnu.io.SerialPortEvent;
  4. import gnu.io.SerialPortEventListener;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.util.Enumeration;
  9. import java.util.TooManyListenersException;
  10. import java.util.logging.Level;
  11. import java.util.logging.Logger;
  12. import javax.swing.JOptionPane;
  13.  
  14. /**
  15.  *
  16.  * @author Ángel Acaymo M. G. (Meta).
  17.  */
  18. //##############################JM################################################
  19. /* La clase debe implementar la interfaz SerialPortEventListener porque esta
  20.  misma clase será la encargada de trabajar con el evento escucha cuando reciba
  21.  datos el puerto serie. */
  22. public class EP_JAVA_Frame extends javax.swing.JFrame implements SerialPortEventListener {
  23. //##############################JM################################################
  24.  
  25.    /**
  26.      * Creates new form EP_JAVA_Frame
  27.      */
  28.    // Variables.
  29.    private static final String Led_8_ON = "Led_8_ON";
  30.    private static final String Led_8_OFF = "Led_8_OFF";
  31.    private static final String Led_13_ON = "Led_13_ON";
  32.    private static final String Led_13_OFF = "Led_13_OFF";
  33.  
  34.    // Variables de conexión.
  35.    private OutputStream output = null;
  36. //##############################JM################################################
  37. /* Así como declaraste una variable ouuput para obtener el canal de salida
  38.      también creamos una variable para obtener el canal de entrada. */
  39.    private InputStream input = null;
  40. //##############################JM################################################
  41.    SerialPort serialPort;
  42.    private final String PUERTO = "COM4";
  43.    private static final int TIMEOUT = 2000; // 2 segundos.
  44.    private static final int DATA_RATE = 115200; // Baudios.
  45.  
  46.    public EP_JAVA_Frame() {
  47.        initComponents();
  48.        inicializarConexion();
  49.    }
  50.  
  51.    public void inicializarConexion() {
  52.        CommPortIdentifier puertoID = null;
  53.        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  54.  
  55.        while (puertoEnum.hasMoreElements()) {
  56.            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  57.            if (PUERTO.equals(actualPuertoID.getName())) {
  58.                puertoID = actualPuertoID;
  59.                break;
  60.            }
  61.        }
  62.  
  63.        if (puertoID == null) {
  64.            mostrarError("No se puede conectar al puerto");
  65.            System.exit(ERROR);
  66.        }
  67.  
  68.        try {
  69.            serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  70.            // Parámatros puerto serie.
  71.  
  72.            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
  73.  
  74.            output = serialPort.getOutputStream();
  75.        } catch (Exception e) {
  76.            mostrarError(e.getMessage());
  77.            System.exit(ERROR);
  78.        }
  79. //##############################JM################################################
  80. /* Aquií asignamos el canal de entrada del puerto serie a nuestra variable input,
  81.          con sus debido capturador de error. */
  82.        try {
  83.            input = serialPort.getInputStream();
  84.        } catch (IOException ex) {
  85.            Logger.getLogger(EP_JAVA_Frame.class.getName()).log(Level.SEVERE, null, ex);
  86.        }
  87.  
  88.        /* Aquí agregamos el evento de escucha del puerto serial a esta misma clase
  89.          (recordamos que nuestra clase implementa SerialPortEventListener), el método que
  90.          sobreescibiremos será serialevent. */
  91.        try {
  92.            serialPort.addEventListener(this);
  93.            serialPort.notifyOnDataAvailable(true);
  94.        } catch (TooManyListenersException ex) {
  95.            Logger.getLogger(EP_JAVA_Frame.class.getName()).log(Level.SEVERE, null, ex);
  96.        }
  97. //##############################JM################################################
  98.    }
  99. //##############################JM################################################
  100. /* Este evento es el que sobreescribiremos de la interfaz SerialPortEventListener,
  101.      este es lanzado cuando se produce un evento en el puerto como por ejemplo
  102.      DATA_AVAILABLE (datos recibidos) */
  103.  
  104.    @Override
  105.    public void serialEvent(SerialPortEvent spe) {
  106.        if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
  107.            byte[] readBuffer = new byte[20];
  108.            try {
  109.                int numBytes = 0;
  110.                while (input.available() > 0) {
  111.                    numBytes = input.read(readBuffer); //Hacemos uso de la variable input que
  112. //creamos antes, input es nuestro canal de entrada.
  113.                }
  114.                jTextArea1.append(new String(readBuffer, 0, numBytes, "us-ascii")); // Convertimos de bytes a String y asignamos al JTEXTAREA.
  115.  
  116.                // Leelos últimos datos.
  117.                jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
  118.            } catch (IOException e) {
  119.                System.out.println(e);
  120.            }
  121.        }
  122.    }
  123. //##############################JM################################################    
  124.  
  125.    private void enviarDatos(String datos) {
  126.        try {
  127.            output.write(datos.getBytes());
  128.        } catch (Exception e) {
  129.            mostrarError("ERROR");
  130.            System.exit(ERROR);
  131.        }
  132.    }
  133.  
  134.    public void mostrarError(String mensaje) {
  135.        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
  136.    }
  137.  
  138.    /**
  139.      * This method is called from within the constructor to initialize the form.
  140.      * WARNING: Do NOT modify this code. The content of this method is always
  141.      * regenerated by the Form Editor.
  142.      */
  143.    @SuppressWarnings("unchecked")
  144.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  145.    private void initComponents() {
  146.  
  147.        jLabel1 = new javax.swing.JLabel();
  148.        jLabel2 = new javax.swing.JLabel();
  149.        jButton1 = new javax.swing.JButton();
  150.        jButton2 = new javax.swing.JButton();
  151.        jButton3 = new javax.swing.JButton();
  152.        jButton4 = new javax.swing.JButton();
  153.        jScrollPane1 = new javax.swing.JScrollPane();
  154.        jTextArea1 = new javax.swing.JTextArea();
  155.        jLabel3 = new javax.swing.JLabel();
  156.  
  157.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  158.        setTitle("Mini Interfaz Java");
  159.  
  160.        jLabel1.setText("Led 8");
  161.  
  162.        jLabel2.setText("Led 13");
  163.  
  164.        jButton1.setText("ON");
  165.        jButton1.addActionListener(new java.awt.event.ActionListener() {
  166.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  167.                jButton1ActionPerformed(evt);
  168.            }
  169.        });
  170.  
  171.        jButton2.setText("OFF");
  172.        jButton2.addActionListener(new java.awt.event.ActionListener() {
  173.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  174.                jButton2ActionPerformed(evt);
  175.            }
  176.        });
  177.  
  178.        jButton3.setText("ON");
  179.        jButton3.addActionListener(new java.awt.event.ActionListener() {
  180.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  181.                jButton3ActionPerformed(evt);
  182.            }
  183.        });
  184.  
  185.        jButton4.setText("OFF");
  186.        jButton4.addActionListener(new java.awt.event.ActionListener() {
  187.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  188.                jButton4ActionPerformed(evt);
  189.            }
  190.        });
  191.  
  192.        jTextArea1.setColumns(20);
  193.        jTextArea1.setRows(5);
  194.        jScrollPane1.setViewportView(jTextArea1);
  195.  
  196.        jLabel3.setText("Mensajes desde Arduino:");
  197.  
  198.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  199.        getContentPane().setLayout(layout);
  200.        layout.setHorizontalGroup(
  201.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  202.            .addGroup(layout.createSequentialGroup()
  203.                .addContainerGap()
  204.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  205.                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
  206.                    .addGroup(layout.createSequentialGroup()
  207.                        .addComponent(jLabel1)
  208.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  209.                        .addComponent(jLabel2))
  210.                    .addGroup(layout.createSequentialGroup()
  211.                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
  212.                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  213.                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  214.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  215.                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  216.                            .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  217.                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
  218.                    .addGroup(layout.createSequentialGroup()
  219.                        .addComponent(jLabel3)
  220.                        .addGap(0, 0, Short.MAX_VALUE)))
  221.                .addContainerGap())
  222.        );
  223.        layout.setVerticalGroup(
  224.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  225.            .addGroup(layout.createSequentialGroup()
  226.                .addContainerGap()
  227.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  228.                    .addComponent(jLabel1)
  229.                    .addComponent(jLabel2))
  230.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  231.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  232.                    .addComponent(jButton1)
  233.                    .addComponent(jButton3))
  234.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  235.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  236.                    .addComponent(jButton2)
  237.                    .addComponent(jButton4))
  238.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  239.                .addComponent(jLabel3)
  240.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  241.                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  242.                .addContainerGap())
  243.        );
  244.  
  245.        jLabel1.getAccessibleContext().setAccessibleName("jLabel_Led_8");
  246.        jButton1.getAccessibleContext().setAccessibleName("jButton_Led_8_ON");
  247.        jButton2.getAccessibleContext().setAccessibleName("jButton_Led_8_OFF");
  248.        jButton3.getAccessibleContext().setAccessibleName("jButton_Led_13_ON");
  249.        jButton4.getAccessibleContext().setAccessibleName("jButton_Led_13_OFF");
  250.  
  251.        pack();
  252.        setLocationRelativeTo(null);
  253.    }// </editor-fold>                        
  254.  
  255.    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  256.        enviarDatos(Led_8_ON); // Enciende Led 8.
  257.    }                                        
  258.  
  259.    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  260.        enviarDatos(Led_8_OFF); // Apaga Led 8.
  261.    }                                        
  262.  
  263.    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  264.        enviarDatos(Led_13_ON); // Enciende Led 13.
  265.    }                                        
  266.  
  267.    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  268.        enviarDatos(Led_13_OFF); // Apaga Led 13.
  269.    }                                        
  270.  
  271.    /**
  272.      * @param args the command line arguments
  273.      */
  274.    public static void main(String args[]) {
  275.        /* Set the Nimbus look and feel */
  276.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  277.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  278.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  279.          */
  280.        try {
  281.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  282.                if ("Nimbus".equals(info.getName())) {
  283.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  284.                    break;
  285.                }
  286.            }
  287.        } catch (ClassNotFoundException ex) {
  288.            java.util.logging.Logger.getLogger(EP_JAVA_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  289.        } catch (InstantiationException ex) {
  290.            java.util.logging.Logger.getLogger(EP_JAVA_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  291.        } catch (IllegalAccessException ex) {
  292.            java.util.logging.Logger.getLogger(EP_JAVA_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  293.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  294.            java.util.logging.Logger.getLogger(EP_JAVA_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  295.        }
  296.        //</editor-fold>
  297.  
  298.        /* Create and display the form */
  299.        java.awt.EventQueue.invokeLater(new Runnable() {
  300.            public void run() {
  301.                new EP_JAVA_Frame().setVisible(true);
  302.            }
  303.        });
  304.    }
  305.  
  306.    // Variables declaration - do not modify                    
  307.    private javax.swing.JButton jButton1;
  308.    private javax.swing.JButton jButton2;
  309.    private javax.swing.JButton jButton3;
  310.    private javax.swing.JButton jButton4;
  311.    private javax.swing.JLabel jLabel1;
  312.    private javax.swing.JLabel jLabel2;
  313.    private javax.swing.JLabel jLabel3;
  314.    private javax.swing.JScrollPane jScrollPane1;
  315.    private javax.swing.JTextArea jTextArea1;
  316.    // End of variables declaration                  
  317. }
  318.  

Lo he intentado paso por paso, pero no se me da.

Eclipse:
Código
  1. package electronica;
  2.  
  3. import gnu.io.CommPortIdentifier;
  4. import gnu.io.SerialPort;
  5. import gnu.io.SerialPortEvent;
  6. import gnu.io.SerialPortEventListener;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.util.Enumeration;
  11. import java.util.TooManyListenersException;
  12. import java.util.logging.Level;
  13. import java.util.logging.Logger;
  14. import javax.swing.JOptionPane;
  15.  
  16. import javax.swing.JFrame;
  17. import javax.swing.JPanel;
  18. import javax.swing.border.EmptyBorder;
  19. import javax.swing.JButton;
  20. import javax.swing.JTextArea;
  21. import java.awt.EventQueue;
  22.  
  23. public class EP_Java extends JFrame {
  24.  
  25. private JPanel contentPane;
  26.  
  27. /**
  28. * Launch the application.
  29. */
  30. // Variables.
  31.    private static final String Led_ON = "Led_ON";
  32.    private static final String Led_OFF = "Led_OFF";
  33.  
  34.    // Variables de conexión.
  35.    private OutputStream output = null;
  36.    private InputStream input = null;
  37.    SerialPort serialPort;
  38.    private final String PUERTO = "COM4";
  39.    private static final int TIMEOUT = 2000; // 2 segundos.
  40.    private static final int DATA_RATE = 115200; // Baudios.
  41.  
  42. public static void main(String[] args) {
  43. EventQueue.invokeLater(new Runnable() {
  44. public void run() {
  45. try {
  46. EP_Java frame = new EP_Java();
  47. frame.setVisible(true);
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. });
  53. }
  54.  
  55. public EP_Java() {
  56. setTitle("Encender y apagar un Led - Java y Arduino");
  57. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  58. setBounds(100, 100, 450, 300);
  59. contentPane = new JPanel();
  60. contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  61. setContentPane(contentPane);
  62. contentPane.setLayout(null);
  63.  
  64. JButton btnOn = new JButton("ON");
  65. btnOn.setBounds(161, 39, 89, 23);
  66. contentPane.add(btnOn);
  67.  
  68. JButton btnOff = new JButton("OFF");
  69. btnOff.setBounds(161, 73, 89, 23);
  70. contentPane.add(btnOff);
  71.  
  72. JTextArea textArea_Recibir_mensajes = new JTextArea();
  73. textArea_Recibir_mensajes.setBounds(10, 103, 414, 147);
  74. contentPane.add(textArea_Recibir_mensajes);
  75.  
  76. inicializarConexion();
  77. }
  78.  
  79. /**
  80. * Create the frame.
  81. */
  82.    public void inicializarConexion() {
  83.        CommPortIdentifier puertoID = null;
  84.        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  85.  
  86.        while (puertoEnum.hasMoreElements()) {
  87.            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  88.            if (PUERTO.equals(actualPuertoID.getName())) {
  89.                puertoID = actualPuertoID;
  90.                break;
  91.            }
  92.        }
  93.  
  94.        if (puertoID == null) {
  95.            mostrarError("No se puede conectar al puerto");
  96.            System.exit(ERROR);
  97.        }
  98.  
  99.        try {
  100.            serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  101.            // Parámatros puerto serie.
  102.  
  103.            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
  104.  
  105.            output = serialPort.getOutputStream();
  106.        } catch (Exception e) {
  107.            mostrarError(e.getMessage());
  108.            System.exit(ERROR);
  109.        }
  110. //##############################JM################################################
  111. /* Aquií asignamos el canal de entrada del puerto serie a nuestra variable input,
  112.          con sus debido capturador de error. */
  113.        try {
  114.            input = serialPort.getInputStream();
  115.        } catch (IOException ex) {
  116.            Logger.getLogger(EP_Java.class.getName()).log(Level.SEVERE, null, ex);
  117.        }
  118.  
  119.        /* Aquí agregamos el evento de escucha del puerto serial a esta misma clase
  120.          (recordamos que nuestra clase implementa SerialPortEventListener), el método que
  121.          sobreescibiremos será serialevent. */
  122.        try {
  123.            serialPort.addEventListener(this);
  124.            serialPort.notifyOnDataAvailable(true);
  125.        } catch (TooManyListenersException ex) {
  126.            Logger.getLogger(EP_Java.class.getName()).log(Level.SEVERE, null, ex);
  127.        }
  128. //##############################JM################################################
  129.    }
  130.  
  131.  //##############################JM################################################
  132.    /* Este evento es el que sobreescribiremos de la interfaz SerialPortEventListener,
  133.          este es lanzado cuando se produce un evento en el puerto como por ejemplo
  134.          DATA_AVAILABLE (datos recibidos) */
  135.  
  136.        public void serialEvent(SerialPortEvent spe) {
  137.            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
  138.                byte[] readBuffer = new byte[20];
  139.                try {
  140.                    int numBytes = 0;
  141.                    while (input.available() > 0) {
  142.                        numBytes = input.read(readBuffer); //Hacemos uso de la variable input que
  143.    //creamos antes, input es nuestro canal de entrada.
  144.                    }
  145.                    textArea_Recibir_mensajes.append(new String(readBuffer, 0, numBytes, "us-ascii")); // Convertimos de bytes a String y asignamos al JTEXTAREA.
  146.  
  147.                    // Leelos últimos datos.
  148.                    textArea_Recibir_mensajes.setCaretPosition(textArea_Recibir_mensajes.getDocument().getLength());
  149.                } catch (IOException e) {
  150.                    System.out.println(e);
  151.                }
  152.            }
  153.        }
  154.    //##############################JM################################################  
  155.  
  156.        private void enviarDatos(String datos) {
  157.            try {
  158.                output.write(datos.getBytes());
  159.            } catch (Exception e) {
  160.                mostrarError("ERROR");
  161.                System.exit(ERROR);
  162.            }
  163.        }
  164.  
  165.        public void mostrarError(String mensaje) {
  166.            JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
  167.        }
  168. }
  169.  

¿Alguna idea?

Saludos.
484  Programación / .NET (C#, VB.NET, ASP) / Limpiar textBox en C# en: 24 Agosto 2017, 22:06 pm
Hola:

En un textbox tengo un contenido, por ejemplo un 0, al hacer clic para escribir, quiero que se borre automáticamente. Nada de seleccoinarlo yo con el ratón y luego borrarlo con Delete. ajjaja.

Lo he intentado de dos maneras y nada.
Código
  1. private void textBox_Tamaño_EEPROM_KeyDown(object sender, KeyEventArgs e)
  2.        {
  3.            textBox_Tamaño_EEPROM.Clear(); // Limpiar.
  4.        }

Y así:
Código
  1.       private void textBox_Tamaño_EEPROM_KeyDown(object sender, KeyEventArgs e)
  2.        {
  3.            textBox_Tamaño_EEPROM.Text = ""; // Limpiar.
  4.        }

A parte de eso, solo me deja escribir hasta un carácter.
485  Programación / .NET (C#, VB.NET, ASP) / Re: Calcular porcentaje en: 22 Agosto 2017, 01:38 am
Averiguado, gracias por la ayuda.

Código
  1.      // Variables.
  2.        bool alto = false;
  3.        int N = 0;
  4.        int P = 0;
  5.        int resul = 0;
  6.  
  7.        private void TestDoEvents()
  8.        {
  9.            // Carga el archivo en el array.
  10.            byte[] archivo = File.ReadAllBytes(textBox_ubicacion_archivo.Text);
  11.  
  12.            // Hasta donde llegue el tamaño del archivo.
  13.            progressBar_barrra_progreso.Maximum = archivo.Length;
  14.  
  15.            // Guarda la cantidad de Bytes del archivo en la variable.
  16.            N = archivo.Length - 1;
  17.  
  18.            // Transmite byte en byte los datos del archivo al puerto serie.
  19.            for (int i = 0; i <= archivo.GetUpperBound(0); i++)
  20.            {
  21.                // Enviando archivo al puerto serie.
  22.                serialPort1.Write(archivo, i, 1);
  23.  
  24.                // Números de Bytes.
  25.                P = i;
  26.  
  27.                // Resultado de la regla de tres. Cálculo del porcentaje de la barra de progreso.
  28.                resul = 100 * i / N;
  29.  
  30.                // Muestra barra del progreso.
  31.                progressBar_barrra_progreso.Value = i;
  32.  
  33.                // Muestra la cantidad de Bytes enviados.
  34.                label_Bytes_transmitidos.Text = i.ToString() + " Bytes.";
  35.  
  36.                // Muestra la cantidad en porciento archivo enviado.
  37.                label_Por_ciento.Text = resul + " %";
  38.  
  39.                // Evento de cancelación.
  40.                Application.DoEvents();
  41.                if (alto == true)
  42.                {
  43.                    alto = false;
  44.                    break; // TODO: might not be correct. Was : Exit For
  45.                }
  46.            }
  47.            button_Cancelar.Text = "Arranque";
  48.        }
  49.  
  50.        private void button_Cancelar_Click(object sender, EventArgs e)
  51.        {
  52.            if (button_Cancelar.Text == "Arranque")
  53.            {
  54.                button_Cancelar.Text = "Cancelar";
  55.                TestDoEvents();
  56.                progressBar_barrra_progreso.Value = 0; // Resetear progressBar a 0.
  57.                label_Bytes_transmitidos.Text = "0";
  58.            }
  59.            else
  60.            {
  61.                if (alto == true)
  62.                {
  63.                    alto = false;
  64.                }
  65.                else
  66.                {
  67.                    alto = true;
  68.                    button_Cancelar.Text = "Arranque";
  69.                }
  70.            }
  71.        }
486  Programación / .NET (C#, VB.NET, ASP) / Re: Calcular porcentaje en: 21 Agosto 2017, 14:36 pm
Buenas:

Pensaba que era algo así.
Código
  1. label_Por_ciento.Text = ((progressBar_barrra_progreso.Value / archivo.Count()) * 100).ToString() + "%";

Voy a probar lo que dices.

Saludos.
487  Programación / .NET (C#, VB.NET, ASP) / Calcular porcentaje en: 21 Agosto 2017, 12:50 pm
Hola:

Hice esta aplicación para enviar datos a EEPROM tipo 24LCxx por I2C con Arduino. Tabajando con C#, ya puedo enviar los datos al puerto serie. Puede contar los bytes enviados. El problema, que estoy machacando la cabeza que no hay manera de hacer fucnionar en la barra del progreso que me cuenta el "label_Por_ciento" del 0 % al 100 %.



Ya puedeo envair datos y cancelarlo.
Código
  1.        private void TestDoEvents()
  2.        {
  3.            byte[] archivo = File.ReadAllBytes(textBox_ubicacion_archivo.Text); // Carga el archivo en el array.
  4.  
  5.            progressBar_barrra_progreso.Maximum = archivo.Length; // Hasta donde llegue el tamaño del archivo.
  6.  
  7.            for (int i = 0; i <= archivo.GetUpperBound(0); i++)
  8.            {
  9.                serialPort1.Write(archivo, i, 1);
  10.  
  11.                progressBar_barrra_progreso.Value = i;
  12.  
  13.                label_Bytes_transmitidos.Text = i.ToString() + " Bytes.";
  14.  
  15.                Application.DoEvents();
  16.                if (alto == true)
  17.                {
  18.                    alto = false;
  19.                    break; // TODO: might not be correct. Was : Exit For
  20.                }
  21.            }
  22.            button_Cancelar.Text = "Arranque";
  23.        }

Botón.
Código
  1.        private void button_Cancelar_Click(object sender, EventArgs e)
  2.        {
  3.            if (button_Cancelar.Text == "Arranque")
  4.            {
  5.                button_Cancelar.Text = "Cancelar";
  6.                TestDoEvents();
  7.                progressBar_barrra_progreso.Value = 0; // Resetear progressBar a 0.
  8.                label_Bytes_transmitidos.Text = "0";
  9.            }
  10.            else
  11.            {
  12.                if (alto == true)
  13.                {
  14.                    alto = false;
  15.                }
  16.                else
  17.                {
  18.                    alto = true;
  19.                    button_Cancelar.Text = "Arranque";
  20.                }
  21.            }
  22.        }

¿Alguna idea?

Saludos.
488  Programación / Java / Re: Encontrar error en el código en: 18 Agosto 2017, 15:42 pm
Código completo.

Código:
package ejercicios;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Prueba01 extends JFrame {

private JPanel contentPane;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Prueba01 frame = new Prueba01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Prueba01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextArea textArea = new JTextArea();


JButton btnMostrar = new JButton("Mostrar");
btnMostrar.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
}
});
btnMostrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

// Variable tipo String.
String variable = "Hola mundo.";

// Mostramos el contenido de la variable en el JTextArea.
textArea.append(variable + "\n");
}
});
btnMostrar.setBounds(165, 11, 89, 23);
contentPane.add(btnMostrar);


textArea.setBounds(10, 55, 414, 195);
contentPane.add(textArea);
}

}

¿Por qué se generó abajo en vez de donde corresponde?

Con NetBeans no pasa.

Gracias por la ayuda.
489  Programación / Programación General / Re: ¿Qué compilador usas? en: 18 Agosto 2017, 01:51 am
Quiero decir IDE y da igual si es masoquismo.  ;-)

490  Programación / Java / Encontrar error en el código en: 18 Agosto 2017, 01:48 am
Hola:

Uso Eclipse oxigeny. En el JFrame puse en el formulario un JButton y un JTextArea. Mi idea es que si pulsas el botón "Mostrar", siga en el JTextArea el mensaje: Hola mundo.



Pulso dos veces el botón Mostrar y me lleva alcódigo.
Código:
				// Variable tipo String.
String variable = "Hola mundo.";

// Mostramos el contenido de la variable en el JTextArea.
textArea.append(variable);

La palabra textArea que es el nombre del JTextArea marca error. No lo detecta. El error indicado es este:
Description   Resource   Path   Location   Type
textArea cannot be resolved   Prueba01.java   /Proyectazo/src/ejercicios   line 53   Java Problem



Código completo:
Código:
package ejercicios;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Prueba01 extends JFrame {

private JPanel contentPane;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Prueba01 frame = new Prueba01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Prueba01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JButton btnMostrar = new JButton("Mostrar");
btnMostrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

// Variable tipo String.
String variable = "Hola mundo.";

// Mostramos el contenido de la variable en el JTextArea.
textArea.append(variable);
}
});
btnMostrar.setBounds(165, 11, 89, 23);
contentPane.add(btnMostrar);

JTextArea textArea = new JTextArea();
textArea.setBounds(10, 55, 414, 195);
contentPane.add(textArea);
}

}

¿Alguna idea?

Saludos.
Páginas: 1 ... 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 [49] 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 ... 255
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines