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


Tema destacado:


  Mostrar Temas
Páginas: 1 ... 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 [18] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ... 68
171  Programación / Programación C/C++ / [SOLUCIONADO] Solucionando errores Menú abrir y cerrar unidad CD-ROM en: 18 Noviembre 2017, 21:06 pm
Hola:

He hecho este programa para poder abrir y cerrar la bandeja con C++ Win32. Lo que tiene que hacer es si pulsa la tecla A, se abre el lector, si pulsas C, cierra la bandeja del lector de discos.

Código
  1. #include "stdafx.h"
  2. #include "stdio.h"
  3. #include "Windows.h"
  4. #include "iostream"
  5. #include "string"
  6. #include "conio.h"
  7.  
  8. using namespace std;
  9.  
  10.  
  11. int main()
  12. {
  13. // Título de la ventana.
  14. SetConsoleTitle(L"Abrir y cerrar bandeja del disco C++ Win32");
  15.  
  16. // Variable
  17. char entrada[] = "\0"; // Guarda A, a, C, y c tipo string que introduces desde la consola.
  18.  
  19. while (true)
  20. {
  21. printf("Control bandeja del lector : \n\n");
  22. printf("A - Abrir bandeja. \n");
  23. printf("C - Cerrar bandeja. \n");
  24. printf("========================== \n\n");
  25.  
  26. cin >> entrada; // Aquí introduces letras A, a, C, y c.
  27.  
  28. switch (srt.tolower(entrada)) // Espera recibir A, a, C, y c. Transforma en minúscula.
  29. {
  30. // Abrir bandeja.
  31. case 'a':
  32. cout << "Abriendo..." << endl; // Muestra en pantalla textos.
  33. //printf("Abriendo...");
  34. // Aquí va un evento para que aparezca la palabra Abirendo... mientra se está abriendo el lector.
  35. mciSendString(L"set cdaudio door open", nullptr, 0, nullptr);
  36. cout << "Abierto." << endl; // Muestra en pantalla textos.
  37. break;
  38.  
  39. // Cerrar bandeja.
  40. case 'b':
  41. cout << "Cerrando..." << endl; // Muestra en pantalla textos.
  42. // Aquí va un evento.
  43. mciSendString(L"set cdaudio door closed", nullptr, 0, nullptr);
  44. cout << "Cerrado." << endl; // Muestra en pantalla textos.
  45. break;
  46.  
  47. default: // Si haz pulsado otro caracter distinto de A, C, a, y c aparece
  48. cout << "Solo pulsar A o C." << endl; // este mensaje.
  49. }
  50. }
  51. return EXIT_SUCCESS;
  52. }
  53.  



¿Qué tengo mal?

Saludos.
172  Programación / Programación General / [SOLUCIONADO] Han cambiado las cosa al actualizar Visual Studio Community 2017 en: 18 Noviembre 2017, 08:27 am
Hola:

 Trabajando con MFC al crear formularios, me salía esta ventana al final en el cual podía ejecutar al pulsar F5 para compilar.
 
 Ver zoom.
 Aquí abajo dejo una guía paso a paso de crear un formulario MFC como se hacía antes desde la página 36, hasta la página 45.
 Ver visor.
 Ver pdf.
 Intenté seguir los pasos, la primera ventana me sale esto.


 No se cual es la mejor forma de hacerlo. Lo dejo tal cual por si acaso y sigo a la página siguiente.
 Sigo el siguiente paso.

 Siguiente paso.

 Siente paso.

 Antes al ejecutar no me daba problemas. Ahora me salen todos estos errores indicado abajo y no se como solucionarlo.

 
¿Hay alguna solución?

 Antes, podía ejecutar la ventana y no pasaba nada.

 Saludos.

PD: Disculpen si no me sale el tamaño adecuado de las capturas.
173  Programación / Programación C/C++ / Adaptar C++ CLR a C++ Win32 en: 16 Noviembre 2017, 12:15 pm
Hola:

Quiero adaptar este código de C++ CLR a C++ Win32. Antes que nada, quiero saber si es posible o hay que complicarse mucho la vida para hacer lo mismo. El código lo que hace es abrir y cerrar la bandeja de cualquier lector de discos sea IDE o SATA.

Aquí encontré un vídeo pero solo ejecuta, y abre el lector en Win32. Por algo se empieza.



Código C++ CLR:
Código
  1. #include "stdafx.h"
  2.  
  3. using namespace System;
  4. using namespace System::Runtime::InteropServices;
  5. using namespace System::Text;
  6.  
  7. [DllImport("winmm.dll")]
  8. extern Int32 mciSendString(String^ lpstrCommand, StringBuilder^ lpstrReturnString,
  9. int uReturnLength, IntPtr hwndCallback);
  10.  
  11. static void DoEvents()
  12. {
  13. Console::SetCursorPosition(0, 6);
  14. Console::Write("Abriendo...");
  15. }
  16.  
  17. static void DoEvents2()
  18. {
  19. Console::SetCursorPosition(0, 6);
  20. Console::Write("Cerrando...");
  21. }
  22.  
  23. int main(array<System::String ^> ^args)
  24. {
  25. StringBuilder^ rt = gcnew StringBuilder(127);
  26.  
  27. // Título de la ventana.
  28. Console::Title = "Control lector de bandeja. C++ CLR";
  29.  
  30. // Tamaño ventana consola.
  31. Console::WindowWidth = 29; // X. Ancho.
  32. Console::WindowHeight = 8; // Y. Alto.
  33.  
  34.  // Cursor invisible.
  35. Console::CursorVisible = false;
  36.  
  37. // Posición del mansaje en la ventana.
  38. Console::SetCursorPosition(0, 0);
  39. Console::WriteLine("Control bandeja del lector : \n\n" +
  40. "A - Abrir bandeja. \n" +
  41. "C - Cerrar bandeja. \n" +
  42. "========================== \n");
  43. //Console::WriteLine("A - Abrir bandeja.");
  44. //Console::WriteLine("C - Cerrar bandeja.");
  45. //Console::Write("==========================");
  46.  
  47. ConsoleKey key;
  48. //Console::CursorVisible = false;
  49. do
  50. {
  51. key = Console::ReadKey(true).Key;
  52.  
  53. String^ mensaje = "";
  54.  
  55. //Asignamos la tecla presionada por el usuario
  56. switch (key)
  57. {
  58. case ConsoleKey::A:
  59. mensaje = "Abriendo...";
  60. Console::SetCursorPosition(0, 6);
  61. DoEvents();
  62. mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);
  63. mensaje = "Abierto.";
  64. break;
  65.  
  66. case ConsoleKey::C:
  67. mensaje = "Cerrando...";
  68. Console::SetCursorPosition(0, 6);
  69. DoEvents2();
  70. mciSendString("set CDAudio door closed", rt, 127, IntPtr::Zero);
  71. mensaje = "Cerrado.";
  72. break;
  73. }
  74.  
  75. Console::SetCursorPosition(0, 6);
  76. Console::Write("           ");
  77. Console::SetCursorPosition(0, 6);
  78. Console::Write(mensaje);
  79.  
  80. } while (key != ConsoleKey::Escape);
  81.    return 0;
  82. }

Saludos.
174  Programación / .NET (C#, VB.NET, ASP) / Hacer funcionar el lector de bandeja de discos con este lenguaje .net en: 15 Noviembre 2017, 21:59 pm
Buenas a todos y a todas:



Quiero pasar este código en consola de C#, VB .net o el C++ CLR a F#. Lo que hace el código es si pulsas A o la letra C abre o cierra la bandeja del lector de discos. A parte de C#, también está en C++ CLR y VB .net por si lo entienden mejor. Lo que hace el código es abrir y cerrar la bandeja de discos del lector, sea IDE o SATA.

Código C#:
Código:
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Lector_teclado_consola_cs
{
    class Program
    {
        [DllImport("winmm.dll")]
        public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,
        int uReturnLength, IntPtr hwndCallback);

        public static StringBuilder rt = new StringBuilder(127);

        public static void DoEvents()
        {
            // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
            Console.SetCursorPosition(0, 6);
            Console.Write("Abriendo...");
        }

        public static void DoEvents2()
        {
            // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
            Console.SetCursorPosition(0, 6);
            Console.Write("Cerrando...");
        }

        static void Main(string[] args)
        {
            // Título de la ventana.
            Console.Title = "Control lector de bandeja. C#";

            // Tamaño ventana consola.
            Console.WindowWidth = 29; // X. Ancho.
            Console.WindowHeight = 8; // Y. Alto.

            // Cursor invisible.
            Console.CursorVisible = false;

            // Posición del mansaje en la ventana.
            Console.SetCursorPosition(0, 0);
            Console.Write(@"Control bandeja del lector:

A - Abrir bandeja.
C - Cerrar bandeja.
===========================");



            ConsoleKey key;
            //Console.CursorVisible = false;
            do
            {
                key = Console.ReadKey(true).Key;

                string mensaje = string.Empty;

                //Asignamos la tecla presionada por el usuario
                switch (key)
                {
                    case ConsoleKey.A:
                        // mensaje = "Abriendo...";
                        Console.SetCursorPosition(0, 6);
                        DoEvents();
                        mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
                        mensaje = "Abierto.";
                        break;

                    case ConsoleKey.C:
                        // mensaje = "Cerrando...";
                        Console.SetCursorPosition(0, 6);
                        DoEvents2();
                        mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero);
                        mensaje = "Cerrado.";
                        break;
                }

                Console.SetCursorPosition(0, 6);
                Console.Write("           ");
                Console.SetCursorPosition(0, 6);
                Console.Write(mensaje);

            }
            while (key != ConsoleKey.Escape);
        }
    }
}

Código VB .net:
Código:
Imports System.Runtime.InteropServices
Imports System.Text

Module Module1
    <DllImport("winmm.dll")>
    Public Function mciSendString(lpstrCommand As String, lpstrReturnString As StringBuilder, uReturnLength As Integer, hwndCallback As IntPtr) As Int32
    End Function

    Public rt As New StringBuilder(127)

    Public Sub DoEvents()
        ' Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
        Console.SetCursorPosition(0, 6)
        Console.Write("Abriendo...")
    End Sub

    Public Sub DoEvents2()
        ' Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
        Console.SetCursorPosition(0, 6)
        Console.Write("Cerrando...")
    End Sub

    Sub Main()
        ' Título de la ventana.
        Console.Title = "Control lector de bandeja. Visual Basic"

        ' Tamaño ventana consola.
        Console.WindowWidth = 29 ' X. Ancho.
        Console.WindowHeight = 8 ' Y. Alto.
        ' Cursor invisible.
        Console.CursorVisible = False

        ' Posición del mansaje en la ventana.
        Console.SetCursorPosition(0, 0)
        Console.Write("Control bandeja del lector:" & vbCr & vbLf & vbCr & vbLf &
                      "A - Abrir bandeja." & vbCr & vbLf &
                      "C - Cerrar bandeja." & vbCr & vbLf &
                      "===========================")

        Dim key As ConsoleKey
        'Console.CursorVisible = false;
        Do
            key = Console.ReadKey(True).Key

            Dim mensaje As String = String.Empty

            'Asignamos la tecla presionada por el usuario
            Select Case key
                Case ConsoleKey.A
                    ' mensaje = "Abriendo...";
                    Console.SetCursorPosition(0, 6)
                    DoEvents()
                    mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero)
                    mensaje = "Abierto."
                    Exit Select

                Case ConsoleKey.C
                    ' mensaje = "Cerrando...";
                    Console.SetCursorPosition(0, 6)
                    DoEvents2()
                    mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero)
                    mensaje = "Cerrado."
                    Exit Select
            End Select

            Console.SetCursorPosition(0, 6)
            Console.Write("           ")
            Console.SetCursorPosition(0, 6)

            Console.Write(mensaje)
        Loop While key <> ConsoleKey.Escape
    End Sub

End Module

Código C++ CLR:
Código:
#include "stdafx.h"

using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Text;

[DllImport("winmm.dll")]
extern Int32 mciSendString(String^ lpstrCommand, StringBuilder^ lpstrReturnString,
int uReturnLength, IntPtr hwndCallback);

static void DoEvents()
{
Console::SetCursorPosition(0, 6);
Console::Write("Abriendo...");
}

static void DoEvents2()
{
Console::SetCursorPosition(0, 6);
Console::Write("Cerrando...");
}

int main(array<System::String ^> ^args)
{
StringBuilder^ rt = gcnew StringBuilder(127);

// Título de la ventana.
Console::Title = "Control lector de bandeja. C++ CLR";

// Tamaño ventana consola.
Console::WindowWidth = 29; // X. Ancho.
Console::WindowHeight = 8; // Y. Alto.

 // Cursor invisible.
Console::CursorVisible = false;

// Posición del mansaje en la ventana.
Console::SetCursorPosition(0, 0);
Console::WriteLine("Control bandeja del lector : \n\n" +
"A - Abrir bandeja. \n" +
"C - Cerrar bandeja. \n" +
"========================== \n");
//Console::WriteLine("A - Abrir bandeja.");
//Console::WriteLine("C - Cerrar bandeja.");
//Console::Write("==========================");

ConsoleKey key;
//Console::CursorVisible = false;
do
{
key = Console::ReadKey(true).Key;

String^ mensaje = "";

//Asignamos la tecla presionada por el usuario
switch (key)
{
case ConsoleKey::A:
mensaje = "Abriendo...";
Console::SetCursorPosition(0, 6);
DoEvents();
mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);
mensaje = "Abierto.";
break;

case ConsoleKey::C:
mensaje = "Cerrando...";
Console::SetCursorPosition(0, 6);
DoEvents2();
mciSendString("set CDAudio door closed", rt, 127, IntPtr::Zero);
mensaje = "Cerrado.";
break;
}

Console::SetCursorPosition(0, 6);
Console::Write("           ");
Console::SetCursorPosition(0, 6);
Console::Write(mensaje);

} while (key != ConsoleKey::Escape);
    return 0;
}

Del .net me falta F# y acabo esta curiosidad y retillo que tengo pendiente desde hace vete a saber.

¿Algún atrevido para poder abrir y cerrar la bandeja del lector usando el lenguaje F#?

Tienes que tener iniciativa para empezar y convencido para terminarlo.

Un cordial saludos a todos y a todas. ;)
175  Programación / .NET (C#, VB.NET, ASP) / Detectar cuando la bandeja del lector está abierta o cerrada en: 12 Noviembre 2017, 01:04 am
Hola:

Aquí hay un código que pulsando A o C abre o cierras la bandeja del lector, a parte de esto, dice Abierto, Abriendo... Cerrado y Cerrando... Todo esto pulsado las teclas A o C.

Me he dado cuenta que si cierro la bandeja directamente con la mano, en la ventana o en el CMD de C#, no lo sabe, se queda en Abierto. La idea es que si cierro la bandeja con la mano, en la pantalla muestre el mensaje.

¿Esto es posible de hacer?

Código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace Lector_teclado_consola_cs
{
    class Program
    {
        [DllImport("winmm.dll")]
        public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,
        int uReturnLength, IntPtr hwndCallback);

        public static StringBuilder rt = new StringBuilder(127);

        public static void DoEvents()
        {
            // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
            Console.SetCursorPosition(0, 6);
            Console.Write("Abriendo...");
        }

        public static void DoEvents2()
        {
            // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
            Console.SetCursorPosition(0, 6);
            Console.Write("Cerrando...");
        }

        static void Main(string[] args)
        {
            // Título de la ventana.
            Console.Title = "Control lector de bandeja.";

            // Tamaño ventana consola.
            Console.WindowWidth = 55; // X. Ancho.
            Console.WindowHeight = 18; // Y. Alto.

            // Cursor invisible.
            Console.CursorVisible = false;

            // Posición del mansaje en la ventana.
            Console.SetCursorPosition(0, 0);
            Console.Write(@"Control bandeja del lector:

A - Abrir bandeja.
C - Cerrar bandeja.
===========================");



            ConsoleKey key;
            //Console.CursorVisible = false;
            do
            {
                key = Console.ReadKey(true).Key;

                string mensaje = string.Empty;

                //Asignamos la tecla presionada por el usuario
                switch (key)
                {
                    case ConsoleKey.A:
                        // mensaje = "Abriendo...";
                        Console.SetCursorPosition(0, 6);
                        DoEvents();
                        mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
                        mensaje = "Abierto.";
                        break;

                    case ConsoleKey.C:
                        // mensaje = "Cerrando...";
                        Console.SetCursorPosition(0, 6);
                        DoEvents2();
                        mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero);
                        mensaje = "Cerrado.";
                        break;
                }

                Console.SetCursorPosition(0, 6);
                Console.Write("           ");
                Console.SetCursorPosition(0, 6);
                Console.Write(mensaje);

            } while (key != ConsoleKey.Escape);
        }
    }
}

Sólo debo modificar o ampliar esa función que falta para dejar el programa más completo.

Saludos.
176  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.
177  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.
178  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.
179  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.
180  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 ... 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 [18] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ... 68
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines