Arduino and Java can't display data in GUI

I use Arduino and java code from this web " www.arduino.cc/playground/Interfacing/Java " in Netbeans.I read data from serial port and I can display data in command line. But I want to display data in jTextArea .It doesn't have anything in jTextArea when I run this code, but have data in command line.How to display data from serial port in jTextArea1.

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

public class SerialTest extends javax.swing.JFrame implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. /
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM5", // Windows
};
/
* Buffered input stream from the port /
private InputStream input;
/
* The output stream to the port /
private OutputStream output;
/
* Milliseconds to block while waiting for port open /
private static final int TIME_OUT = 2000;
/
* Default bits per second for COM port. */
private static final int DATA_RATE = 9600;

/** Creates new form SerialTest */
public SerialTest() {
initComponents();
}

public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

// iterate through, looking for the port
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}

if (portId == null) {
System.out.println("Could not find COM port.");
return;
}

try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);

// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

// open the streams
input = serialPort.getInputStream();
output = serialPort.getOutputStream();

// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}

/**

  • This should be called when you stop using the port.
  • This will prevent port locking on platforms like Linux.
    */
    public synchronized void close() {
    if (serialPort != null) {
    serialPort.removeEventListener();
    serialPort.close();
    }
    }

/**

  • Handle an event on the serial port. Read the data and print it.
    */
    public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
    try {
    int available = input.available();
    byte chunk[] = new byte[available];
    input.read(chunk, 0, available);

// Displayed results are codepage dependent
System.out.print(new String(chunk)); // I can display data here in command line.
jTextArea1.append(new String(chunk)); // I can't display data here in jTextField1.
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
/** This method is called from within the constructor to

  • initialize the form.
  • WARNING: Do NOT modify this code. The content of this method is
  • always regenerated by the Form Editor.
    */
    @SuppressWarnings("unchecked")
    //
    private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField1 = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

jTextField1.setText("jTextField1");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(19, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(44, Short.MAX_VALUE))
);

pack();
}//

/**

  • @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new SerialTest().setVisible(true);
    }
    });
    SerialTest main = new SerialTest();
    main.initialize();
    System.out.println("Started");

}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration

}

I'm not a Java guru by any means, but in your code it looks like you declare the jTextArea1 in one function/method of your class, but that variable isn't declared as private in the class itself, and so isn't it only in scope at the place where you declare it, then when you go to use it in the other method (serialEvent) it is out-of-scope, and thus inaccessible in that method? That's just a guess... :stuck_out_tongue:

It seems that you're calling setVisible on a new SerialTest object, rather than the one you've initialised:

   public static void main(String args[]) {
       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               [glow]new SerialTest().setVisible(true);[/glow]
           }
       });
                   SerialTest main = new SerialTest();
           main.initialize();
           System.out.println("Started");

   }

I'm not really sure what the purpose of making the SerialTest visible in a separate thread is, but this may work:

   public static void main(String args[]) {
           [glow]SerialTest main = new SerialTest();[/glow]
           main.initialize();
           System.out.println("Started");

       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               [glow]main[/glow].setVisible(true);
           }
       });
                   


   }

It doesn't work. It have error . I think EDT can't display data in GUI .Now I seperate code SerialTest class for read data from serial port and send to ShowSerial class for display data.

ShowSerial SS = new ShowSerial()
SS.displaySerialData((new String(chunk));

and display in Class ShowSerial here.

              public void displaySerialData (String data) {
                  jTextArea1.append(data);
                  System.out.println(data);
             }

but I don't know how to use SwingWorker with this code.
I use code for read serial port from this web
www.arduino.cc/playground/Interfacing/Java
It can display data in command line only.

I used SwingWorker with this code but It doesn't work too .I don't know how to display data in jTextArea1. :-[

public synchronized void serialEvent(SerialPortEvent oEvent) {
            if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {


      new SwingWorker<Void, String>()
      {


        @Override
        protected Void doInBackground() throws Exception
        {
                             /**if command available hardware respone data here**/
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input, "tis-620"));
                    String line = "";
     while ((line = reader.readLine()) != null) {
                        if (line.length() > 0) {
                         publish(line);
                        }
                    }

          return null;
        }

        @Override
        protected void process(List<String> chunks)
        {
          for (String string : chunks)
          {
         TS.displaySerialData(string);
          }
        }

        @Override
        protected void done()
        {
         // source.setEnabled(true);
        }

      }.execute();


                }

            // Ignore all the other eventTypes, but you should consider the other ones.
      }

}

When I use this code It can't display anything in jTextArea1 .

              public void displaySerialData (String data) {
                  //  jTextArea1.append(data);
                   jTextArea1.append("aaaaa");    //  It not show aaaaa
                  System.out.println(data);
                 
              }

Now I can display in GUI .I not use SwingWorker . Thank you very much. ;D ;D ;D ;D ;D

For me it is not clear how you resolved this problem. Could you post your sample code, please?