swingworker

Hey Guys

Am sending data to the serial port a byte at a time and a response is recieved at the serialport for every sent byte.

My problem is that all the responses are displayed in the application after all the bytes are sent. I want each response to be shown in the application when it's recieved and not after all the bytes are sent. I am trying to use the swingworker to manage my threads, but I just cannot get it to work. Plze give me a hand

NB. I have attached the class ttteer which runs the GUI and the class SimpleRead.java which has the method "serialEvent(SerialPortEvent event)" that reads from the serial port when ever there is an event and the method writeToport() that writes to the port.

import java.io.*;

import java.util.*;

import javax.comm.*;

import javax.swing.SwingWorker;

publicclass SimpleReadextends SwingWorker <String, String>implements SerialPortEventListener{

//public class SimpleRead implements SerialPortEventListener {

privatestaticfinal String SERIALPORT ="COM1";

private CommPortIdentifier portId;

private Enumeration portList;

public InputStream inputStream;

private SerialPort serialPort;

publicstatic String data ="";

private ttteer parent;

public OutputStream outputStream ;

publicstatic contents_of_afile content =new contents_of_afile();

publicstatic browse11 browse =new browse11();

staticbyte[] dataVector =newbyte[10000];

Thread readThread;

public SimpleRead(ttteer parent){

this.parent = parent;

portList = CommPortIdentifier.getPortIdentifiers();

while (portList.hasMoreElements()){

portId = (CommPortIdentifier) portList.nextElement();

if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){

if (portId.getName().equals(SERIALPORT)){

try{

serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);

inputStream = serialPort.getInputStream();

outputStream = serialPort.getOutputStream();

serialPort.addEventListener(this);

serialPort.notifyOnDataAvailable(true);

serialPort.setSerialPortParams(9600,

SerialPort.DATABITS_8,

SerialPort.STOPBITS_1,

SerialPort.PARITY_NONE);

}catch (Exception e){

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

publicvoid serialEvent(SerialPortEvent event){

switch(event.getEventType()){

//case SerialPortEvent.BI:

//case SerialPortEvent.OE:

//case SerialPortEvent.FE:

//case SerialPortEvent.PE:

//case SerialPortEvent.CD:

//case SerialPortEvent.CTS:

//case SerialPortEvent.DSR:

//case SerialPortEvent.RI:

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

break;

case SerialPortEvent.DATA_AVAILABLE:

byte[] readBuffer =newbyte[1];

try{

while (inputStream.available() > 0){

int numBytes = inputStream.read(readBuffer);

data =new String(readBuffer);

//System.out.print(data);

//parent.setData(data);

publish(data);

nothing(numBytes);

}

}catch (IOException e){

e.printStackTrace();

}

break;

}

try{

inputStream.close();

}catch (IOException e){

}

}

int nothing(int ui){

return ui;

}

publicvoid writeToport(){

String sfile = browse.onBrowseSwing();//gets the method that returns the file name

if(sfile ==null){

System.out.println("sfile er null");

}

File file =new File(sfile);//get the file to be sent... this is actually supposed to be from browse

if(file ==null){

System.out.println("file er null");

}

try{

dataVector = contents_of_afile.getBytesFromFile(file);//the file is loaded in the dataVector

}catch(IOException e){

}

try{

int len = dataVector.length;

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

byte sent_byte = dataVector[i];

if(dataVector[i] == 0x0D && dataVector[i+1] == 0x0A){

try{

Thread.sleep(190);

}

catch(InterruptedException e){

}

if(dataVector ==null){

System.out.println("dataVector er null");

}

}else{

outputStream.write(sent_byte);

}

}

}catch(IOException e){

}

}

public String doInBackground(){

// do the serial port writing

//writeToport();

// when the session finishes, return whatever result you want,

// & retrieve it with a SwingWorker.get() method

return"";

}

protectedvoid process(List<String> eventDataChunks){

// send each piece of event data to the GUI

for (String eventData : eventDataChunks){

parent.setData(eventData);

System.out.print(eventData);

}

}

}

import java.awt.*;

import java.awt.event.*;

import javax.swing.SwingUtilities;

import javax.swing.KeyStroke;

import javax.swing.*;

import java.io.IOException;

import javax.swing.JTextArea;

publicclass ttteer{

private JFrame jFrame =new JFrame();

private JPanel jContentPane =new JPanel();

private JMenuBar jJMenuBar =new JMenuBar();

private JMenu fileMenu =new JMenu();

private JMenu editMenu =new JMenu();

private JMenuItem sendMenuItem =new JMenuItem();

private JMenuItem printMenuItem =new JMenuItem();

private JMenuItem ClearScrean =new JMenuItem();

private JMenuItem cutMenuItem =new JMenuItem();

private JMenuItem copyMenuItem =new JMenuItem();

private JMenuItem pasteMenuItem =new JMenuItem();

private JMenuItem saveMenuItem =new JMenuItem();

browse11 gennemse =new browse11();

private SimpleRead read;// = new SimpleRead(this);

JTextArea dataArea =new JTextArea(" ",20,30);

JScrollPane pane =new JScrollPane(dataArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

public ttteer(){

read =new SimpleRead(this);

read.execute();

}

private JFrame getJFrame()throws IOException{

jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jFrame.setJMenuBar(getJJMenuBar());

jFrame.setSize(400, 400);

jFrame.setContentPane(getJContentPane());

jFrame.setTitle("Deos Tera term");

return jFrame;

}

private JPanel getJContentPane(){

jContentPane.setLayout(new FlowLayout());//FlowLayerout viser nogettttttttttttttttttttt

jContentPane.add(pane);

return jContentPane;

}

private JMenuBar getJJMenuBar()throws IOException{

jJMenuBar.add(getFileMenu());

jJMenuBar.add(getEditMenu());

return jJMenuBar;

}

private JMenu getFileMenu()throws IOException{

fileMenu.setText("File");

fileMenu.add(getSaveMenuItem());

fileMenu.add(getSendMenuItem());

fileMenu.add(getClearScrean());

fileMenu.add(getPrint());

return fileMenu;

}

private JMenu getEditMenu(){

editMenu.setText("Edit");

editMenu.add(getCutMenuItem());

editMenu.add(getCopyMenuItem());

editMenu.add(getPasteMenuItem());

return editMenu;

}

private JMenuItem getSendMenuItem()throws IOException{

sendMenuItem.setText("send file");

sendMenuItem.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent e){

read.writeToport();

}

});

return sendMenuItem;

}

private JMenuItem getClearScrean()throws IOException{

ClearScrean.setText("Clear Screan");

ClearScrean.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent e){

dataArea.setText(" ");

}

});

return ClearScrean;

}

private JMenuItem getPrint()throws IOException{

printMenuItem.setText("Print");

printMenuItem.addActionListener(new Printer(dataArea));

return printMenuItem;

}

publicvoid setData(String txt){//heeeeeeeeeerrrrrrrrrrrrrrrrrrrrr

dataArea.append(txt);

dataArea.setEditable(true);

}

private JMenuItem getCutMenuItem(){

cutMenuItem.setText("Cut");

cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,

Event.CTRL_MASK,true));

return cutMenuItem;

}

private JMenuItem getCopyMenuItem(){

copyMenuItem.setText("Copy");

copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,

Event.CTRL_MASK,true));

return copyMenuItem;

}

private JMenuItem getPasteMenuItem(){

pasteMenuItem.setText("Paste");

pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,

Event.CTRL_MASK,true));

return pasteMenuItem;

}

private JMenuItem getSaveMenuItem(){

saveMenuItem.setText("Save");

saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,

Event.CTRL_MASK,true));

saveMenuItem.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent e){

SavaData save1 =new SavaData();

save1.save(dataArea);

}

});

return saveMenuItem;

}

publicstaticvoid main(String[] args)throws IOException{

SwingUtilities.invokeLater(new Runnable(){

publicvoid run(){

try{

ttteer application =new ttteer();

application.getJFrame().setVisible(true);

}catch(IOException w){

}

}

});

}

}

[19862 byte] By [musiigea] at [2007-11-27 11:32:29]
# 1

Use SwingUtilities.invokeAndWait() to update UI from your custom thread. In fact it stops current thread and pass control to EDT to show UI changes.

Regadrs,

Stas

StanislavLa at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...
# 2

Can you plze give me an example? I do not really get you

musiigea at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...
# 3

Is this what u meant

protected void process(final List<String> eventDataChunks) {

final Runnable doHelloWorld = new Runnable() {

public void run() {

// send each piece of event data to the GUI

for (String eventData : eventDataChunks) {

parent.setData(eventData);

System.out.print(eventData);

}

}

};

Thread appThread = new Thread() {

public void run() {

try {

SwingUtilities.invokeAndWait(doHelloWorld);

}

catch (Exception e) {

e.printStackTrace();

}

//System.out.println("Finished on " + Thread.currentThread());

}

};

appThread.start();

}

musiigea at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...
# 4

Yes. Something like this.

If you e.g. call someLabel.setText() in a separate thread you won't see the changes but if you surround the call with invokeAndWait the thread will be stopped and EDT will update the label.

Regards,

Stas

StanislavLa at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...
# 5

thanks but I still get the responses from the serialport displayed in the GUI after the sending is completed. What am I missing?

musiigea at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...
# 6

I have modifeid the code below to use SwingUtilities.invokeAndWait to update the GUI whenever data is detected on the serial port. But It just does't work... what am I doing wrong guys?

import java.io.*;

import java.util.*;

import javax.comm.*;

import javax.swing.*;

public class SimpleRead extends Thread implements SerialPortEventListener {

private static final String SERIALPORT = "COM1";

private CommPortIdentifier portId;

private Enumeration portList;

public InputStream inputStream;

private SerialPort serialPort;

public static String data = "";

private GUI parent;

public OutputStream outputStream ;

public static contents_of_afile content = new contents_of_afile();

public static browse11 browse = new browse11();

static byte[] dataVector = new byte[10000];

public String ttdata;

public SimpleRead(GUI parent){

this.parent = parent;

portList = CommPortIdentifier.getPortIdentifiers();

while (portList.hasMoreElements()) {

portId = (CommPortIdentifier) portList.nextElement();

if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

if (portId.getName().equals(SERIALPORT)) {

try {

serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);

inputStream = serialPort.getInputStream();

outputStream = serialPort.getOutputStream();

serialPort.addEventListener(this);

serialPort.notifyOnDataAvailable(true);

serialPort.setSerialPortParams(9600,

SerialPort.DATABITS_8,

SerialPort.STOPBITS_1,

SerialPort.PARITY_NONE);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

public void serialEvent(final SerialPortEvent event) { //gets data from the serial port whenever there is an event

switch(event.getEventType()) {

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

break;

case SerialPortEvent.DATA_AVAILABLE:

byte[] readBuffer = new byte[1];

try {

while (inputStream.available() > 0) {

int numBytes = inputStream.read(readBuffer);

data = new String(readBuffer);

ttdata = data;

publishData();

nothing(numBytes);

}

} catch (IOException e) {

e.printStackTrace();

}

break;

}

try{

inputStream.close();

}catch (IOException e){

}

}

int nothing(int ui){

return ui;

}

public void publishData(){ //sets the data in the gui

final Runnable doHelloWorld = new Runnable() {

public void run() {

parent.setData(ttdata);

}

};

Thread appThread = new Thread() {

public void run() {

try {

SwingUtilities.invokeAndWait(doHelloWorld);

}

catch (Exception e) {

e.printStackTrace();

}

//System.out.println("Finished on " + Thread.currentThread());

}

};

appThread.start();

System.out.print("test reached");

}

public void writeToport(){ //writes to the serial port

String sfile = browse.onBrowseSwing();//gets the method that returns the file name

if(sfile == null){

System.out.println("sfile er null");

}

File file = new File(sfile);//get the file to be sent... this is actually supposed to be from browse

if(file == null){

System.out.println("file er null");

}

try{

dataVector = contents_of_afile.getBytesFromFile(file);//the file is loaded in the dataVector

} catch(IOException e){

}

try{

int len = dataVector.length;

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

byte sent_byte = dataVector[i];

if(dataVector[i] == 0x0D && dataVector[i+1] == 0x0A){

try{

Thread.sleep(190);

}

catch(InterruptedException e){

}

if(dataVector == null){

System.out.println("dataVector er null");

}

}else{

outputStream.write(sent_byte);

}

}

}catch(IOException e){

}

}

}

musiigea at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...
# 7

From the code I don't see what is the GUI part. Where are all the labels? textfields etc?

All the controls which shows progress?

If publishData() the code should look like:

{code]

public void publishData(){ //sets the data in the gui

final Runnable doHelloWorld = new Runnable() {

public void run() {

parent.setData(ttdata);

}

};

SwingUtilities.invokeAndWait(doHelloWorld);

System.out.print("test reached");

}

[/code]

No need to create one more thread because your class is thread.

Regards,

Stas

StanislavLa at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...
# 8

the part marked with //***

public void publishData(){ //sets the data in the gui

final Runnable doHelloWorld = new Runnable() {

public void run() {

parent.setData(ttdata);//***

}

};

Thread appThread = new Thread() {

public void run() {

try {

SwingUtilities.invokeAndWait(doHelloWorld);

}

catch (Exception e) {

e.printStackTrace();

}

//System.out.println("Finished on " + Thread.currentThread());

}

};

appThread.start();

System.out.print("test reached");

}

musiigea at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...
# 9

The code for the GUI class is in the posted question

musiigea at 2007-7-29 16:45:46 > top of Java-index,Desktop,Core GUI APIs...