public CommPortIdentifier portId; // @jve:decl-index=0: public SerialPort serialPort;
InputStream inputStream; OutputStream outputStream; String str = ""; // @jve:decl-index=0: private Group group1 = null; private List list = null; public COM() { // TODO Auto-generated constructor stub } /** * This method initializes viewForm * */ private void createViewForm() { viewForm = new ViewForm(sShell, SWT.NONE); createComposite(); viewForm.setTopLeft(composite); createGroup1(); viewForm.setContent(group1); //viewForm.setTopCenter(group1);
} /** * This method initializes composite * */ private void createComposite() { composite = new Composite(viewForm, SWT.BORDER); composite.setLayout(new FillLayout()); createGroup(); } /** * This method initializes group * */ private void createGroup() { GridData gridData2 = new GridData(); gridData2.horizontalAlignment = GridData.FILL; gridData2.horizontalSpan = 21; gridData2.verticalAlignment = GridData.CENTER; GridLayout gridLayout1 = new GridLayout(); gridLayout1.numColumns = 24; gridLayout1.marginWidth = 10; gridLayout1.horizontalSpacing = 10; group = new Group(composite, SWT.NONE); group.setText("串口"); group.setLayout(gridLayout1); Label filler2 = new Label(group, SWT.NONE); filler2.setText("串口:"); createCombo(); button = new Button(group, SWT.NONE); button.setText("连接"); button.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() if(!inviateCOMM()) return; } }); button2 = new Button(group, SWT.NONE); button2.setText("断开"); button2.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() serialPort.close();
} }); Label filler3 = new Label(group, SWT.NONE); filler3.setText("发送:"); text = new Text(group, SWT.BORDER); text.setLayoutData(gridData2); button1 = new Button(group, SWT.NONE); button1.setText("发送"); button1.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected() sendData();
} }); } /** * This method initializes combo * */ private void createCombo() { GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.horizontalSpan = 21; gridData.verticalAlignment = GridData.CENTER; combo = new Combo(group, SWT.NONE); combo.setLayoutData(gridData); combo.add("COM1", 0); combo.add("COM2", 1); combo.add("COM3", 2); combo.add("COM4", 3); combo.add("COM5", 4); combo.select(0); } /** * This method initializes group1 * */ private void createGroup1() { group1 = new Group(viewForm, SWT.NONE); group1.setText("数据信息"); group1.setLayout(new FillLayout()); list = new List(group1, SWT.NONE); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub /* Before this is run, be sure to set up the launch configuration (Arguments->VM Arguments) * for the correct SWT library path in order to run with the SWT dlls. * The dlls are located in the SWT plugin jar. * For example, on Windows the Eclipse SWT 3.1 plugin jar is: * installation_directory\plugins\org.eclipse.swt.win32_3.1.0.jar */ Display display = Display.getDefault(); COM thisClass = new COM(); thisClass.createSShell(); thisClass.sShell.open(); while (!thisClass.sShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } /** * This method initializes sShell */ private void createSShell() { sShell = new Shell(); sShell.setText("串口通讯"); createViewForm(); sShell.setSize(new Point(362, 375)); sShell.setLayout(new FillLayout()); sShell.layout(true);
private void handleVRSelected() { totalColumnList.clear(); for (int i = 0; i < mVRList.getSelectionIndices().length; i++) { int index = mVRList.getSelectionIndices()[i]; Entity entity = EntityUtil.getEntityList(mContainer).get(index); totalColumnList.addAll(entity.getColumnList()); } int size = totalColumnList.size(); String viewColNames[] = new String[size]; for (int i = 0; i < size; i++) { viewColNames[i] = totalColumnList.get(i).getParentEntity().getName() + "." + NamedItemUtil.getDisplayNameList(totalColumnList, false)[i]; } mVLList.setItems(viewColNames); } private void makeViewReferenceList() { for (int i = 0; i < mVRList.getSelectionIndices().length; i++) { int indexEntity = mVRList.getSelectionIndices()[i]; Entity entity = EntityUtil.getEntityList(mContainer).get(indexEntity); ReferenceUtil.getReferenceTo(mViewNew, entity); // create View Reference ViewReference viewRef = dmFactoryImpl.init().createViewReference(); viewRef.setReferenceType(ReferenceType.ENTITY); viewRef.setParentView(mViewNew); viewRef.setEntityId(entity.getUID()); ViewReferenceUtil.setViewReferenceDefaultRefAlias(viewRef, mContainer); mViewNew.getViewReferenceList().add(viewRef); // create View Column list for (int j = 0; j < mVLList.getSelectionIndices().length; j++) { int indexColumn = mVLList.getSelectionIndices()[j]; Column column = totalColumnList.get(indexColumn); if (column.getParentEntity() == entity) { ViewColumn viewCol = dmFactoryImpl.init().createViewColumn(); viewCol.setViewReference(viewRef); ViewColumnUtil.setViewColumnDefaultValue(viewCol, column); mViewNew.getViewColumnList().add(viewCol); } } } } protected void okPressed() { makeViewReferenceList(); super.okPressed(); } } 你报了什么异常?
Exception in thread "Win32SerialPort Notification thread" org.eclipse.swt.SWTException: Invalid thread access at org.eclipse.swt.SWT.error(SWT.java:3374) at org.eclipse.swt.SWT.error(SWT.java:3297) at org.eclipse.swt.SWT.error(SWT.java:3268) at org.eclipse.swt.widgets.Widget.error(Widget.java:435) at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:331) at org.eclipse.swt.widgets.List.add(List.java:94) at COM.serialEvent(COM.java:256) at com.sun.comm.Win32SerialPort.sendDataAvailEvent(Win32SerialPort.java:649) at com.sun.comm.NotificationThread.run(Win32SerialPort.java:878)
然后在接口的实现代码中调用一个list
但出现异常
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.layout.GridData;
import com.sun.org.apache.xpath.internal.operations.Bool;
import javax.comm.*;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.TooManyListenersException;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.layout.FormLayout;public class COM implements SerialPortEventListener{ private Shell sShell = null; // @jve:decl-index=0:visual-constraint="10,10"
private ViewForm viewForm = null;
private Composite composite = null;
private Group group = null;
private Combo combo = null;
private Button button = null;
private Text text = null;
private Button button1 = null;
private Button button2 = null;
public CommPortIdentifier portId; // @jve:decl-index=0: public SerialPort serialPort;
InputStream inputStream; OutputStream outputStream;
String str = ""; // @jve:decl-index=0:
private Group group1 = null;
private List list = null;
public COM() {
// TODO Auto-generated constructor stub
} /**
* This method initializes viewForm
*
*/
private void createViewForm() {
viewForm = new ViewForm(sShell, SWT.NONE);
createComposite();
viewForm.setTopLeft(composite);
createGroup1();
viewForm.setContent(group1);
//viewForm.setTopCenter(group1);
} /**
* This method initializes composite
*
*/
private void createComposite() {
composite = new Composite(viewForm, SWT.BORDER);
composite.setLayout(new FillLayout());
createGroup();
} /**
* This method initializes group
*
*/
private void createGroup() {
GridData gridData2 = new GridData();
gridData2.horizontalAlignment = GridData.FILL;
gridData2.horizontalSpan = 21;
gridData2.verticalAlignment = GridData.CENTER;
GridLayout gridLayout1 = new GridLayout();
gridLayout1.numColumns = 24;
gridLayout1.marginWidth = 10;
gridLayout1.horizontalSpacing = 10;
group = new Group(composite, SWT.NONE);
group.setText("串口");
group.setLayout(gridLayout1);
Label filler2 = new Label(group, SWT.NONE);
filler2.setText("串口:");
createCombo();
button = new Button(group, SWT.NONE);
button.setText("连接");
button.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected()
if(!inviateCOMM())
return;
}
});
button2 = new Button(group, SWT.NONE);
button2.setText("断开");
button2.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected()
serialPort.close();
}
});
Label filler3 = new Label(group, SWT.NONE);
filler3.setText("发送:");
text = new Text(group, SWT.BORDER);
text.setLayoutData(gridData2);
button1 = new Button(group, SWT.NONE);
button1.setText("发送");
button1.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
System.out.println("widgetSelected()"); // TODO Auto-generated Event stub widgetSelected()
sendData();
}
});
} /**
* This method initializes combo
*
*/
private void createCombo() {
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 21;
gridData.verticalAlignment = GridData.CENTER;
combo = new Combo(group, SWT.NONE);
combo.setLayoutData(gridData);
combo.add("COM1", 0);
combo.add("COM2", 1);
combo.add("COM3", 2);
combo.add("COM4", 3);
combo.add("COM5", 4);
combo.select(0);
} /**
* This method initializes group1
*
*/
private void createGroup1() {
group1 = new Group(viewForm, SWT.NONE);
group1.setText("数据信息");
group1.setLayout(new FillLayout());
list = new List(group1, SWT.NONE);
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/* Before this is run, be sure to set up the launch configuration (Arguments->VM Arguments)
* for the correct SWT library path in order to run with the SWT dlls.
* The dlls are located in the SWT plugin jar.
* For example, on Windows the Eclipse SWT 3.1 plugin jar is:
* installation_directory\plugins\org.eclipse.swt.win32_3.1.0.jar
*/
Display display = Display.getDefault();
COM thisClass = new COM();
thisClass.createSShell();
thisClass.sShell.open(); while (!thisClass.sShell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
} /**
* This method initializes sShell
*/
private void createSShell() {
sShell = new Shell();
sShell.setText("串口通讯");
createViewForm();
sShell.setSize(new Point(362, 375));
sShell.setLayout(new FillLayout());
sShell.layout(true);
}
private boolean inviateCOMM()
{
String temp = combo.getText();
System.out.print(temp);
try {
portId = CommPortIdentifier.getPortIdentifier(temp);
} catch (NoSuchPortException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
serialPort = (SerialPort) portId.open("ReadComm", 2000);
} catch (PortInUseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
MessageDialog.openInformation(null, "错误", "串口"+temp+"打开失败");
return false;
}
try {
serialPort.setSerialPortParams(19200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* 侦听到串口有数据,触发串口事件 */
serialPort.notifyOnDataAvailable(true);
return true;
} public void serialEvent(SerialPortEvent arg0) {
// TODO Auto-generated method stub
RecData();
}
private void sendData()
{
byte data[] = new byte[1024];
data = (text.getText()).getBytes(); try {
outputStream.write(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list.add("Send: "+ text.getText());
}
private void RecData()
{
byte[] readBuffer = new byte[1024];
/* 从线路上读取数据流 */
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // while end str = new String(readBuffer);
/* 接收到的数据存放到文本区中 */
System.out.print(str);
list.add("3434234");
}
}
// TODO Auto-generated method stublist.add("4324234");//异常}
可以简化成这样!!!!
// TODO Auto-generated method stublist.add("4324234");//异常}
可以简化成这样!!!!
}
这个应该是实现SerialPortEventListener接口的方法,我没这个接口,无法测试你的程序,我有一个类似的程序
试过了,没什么问题。 红色是测试加的代码import java.util.ArrayList;import jp.co.intramart.app.producer.db.dm.diagram.util.ResourceMessages;
import jp.co.intramart.app.producer.db.dm.diagram.util.model.EntityUtil;
import jp.co.intramart.app.producer.db.dm.diagram.util.model.NamedItemUtil;
import jp.co.intramart.app.producer.db.dm.diagram.util.model.ReferenceUtil;
import jp.co.intramart.app.producer.db.dm.diagram.util.model.ViewColumnUtil;
import jp.co.intramart.app.producer.db.dm.diagram.util.model.ViewReferenceUtil;
import jp.co.intramart.app.producer.db.dm.impl.dmFactoryImpl;
import jp.co.intramart.app.producer.db.dm.model.Column;
import jp.co.intramart.app.producer.db.dm.model.DataModelDiagram;
import jp.co.intramart.app.producer.db.dm.model.Entity;
import jp.co.intramart.app.producer.db.dm.model.View;
import jp.co.intramart.app.producer.db.dm.model.ViewColumn;
import jp.co.intramart.app.producer.db.dm.model.ViewReference;
import jp.co.intramart.app.producer.db.dm.type.ReferenceType;import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;public class SetViewReferenceDialog extends Dialog { private Label mTabelLabel;
private Label mViewAttributeLabel;
private List mVRList;
private List mVLList; private java.util.List<Column> totalColumnList = new ArrayList<Column>(); private DataModelDiagram mContainer;
private View mViewNew; private static String lblDialogTitle = ResourceMessages.getString("SetViewRefDialogTitle_TITLE");
private static String lblDialogChooseTable = ResourceMessages.getString("SetViewRefDialogLabel_CHOOSETABLE");
private static String lblDialogChooseColumn = ResourceMessages.getString("SetViewRefDialogLabel_CHOOSECOLUMN"); public SetViewReferenceDialog(Shell parentShell, DataModelDiagram container, View view) {
super(parentShell);
mContainer = container;
mViewNew = view;
setShellStyle(getShellStyle() | SWT.APPLICATION_MODAL | SWT.RESIZE);
} protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(lblDialogTitle);
} protected Control createDialogArea(Composite parent) { Composite result = (Composite) super.createDialogArea(parent);
result.setSize(300, 300);
createChoosePanel(result);
return result;
} private void createChoosePanel(Composite parent) { Composite panel = new Composite(parent, 0);
GridLayout layout = new GridLayout(2, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
panel.setLayout(layout);
panel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); mTabelLabel = new Label(panel, 16384);
mTabelLabel.setText(lblDialogChooseTable); mViewAttributeLabel = new Label(panel, 16384);
mViewAttributeLabel.setText(lblDialogChooseColumn); mVRList = new List(panel, SWT.BORDER | SWT.MULTI);
GridData gd1 = new GridData(GridData.FILL_HORIZONTAL);
gd1.widthHint = 150;
gd1.heightHint = 200;
mVRList.setLayoutData(gd1);
mVRList.setItems(EntityUtil.getTableNameList(mContainer));
mVRList.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleVRSelected();
change();
}
}); mVLList = new List(panel, SWT.BORDER | SWT.MULTI);
GridData gd2 = new GridData(GridData.FILL_HORIZONTAL);
gd2.widthHint = 200;
gd2.heightHint = 200;
mVLList.setLayoutData(gd2);
} private void change(){
mVRList.add("1235");
}
private void handleVRSelected() {
totalColumnList.clear();
for (int i = 0; i < mVRList.getSelectionIndices().length; i++) {
int index = mVRList.getSelectionIndices()[i];
Entity entity = EntityUtil.getEntityList(mContainer).get(index);
totalColumnList.addAll(entity.getColumnList());
}
int size = totalColumnList.size();
String viewColNames[] = new String[size];
for (int i = 0; i < size; i++) {
viewColNames[i] = totalColumnList.get(i).getParentEntity().getName() + "."
+ NamedItemUtil.getDisplayNameList(totalColumnList, false)[i];
}
mVLList.setItems(viewColNames);
} private void makeViewReferenceList() {
for (int i = 0; i < mVRList.getSelectionIndices().length; i++) {
int indexEntity = mVRList.getSelectionIndices()[i];
Entity entity = EntityUtil.getEntityList(mContainer).get(indexEntity);
ReferenceUtil.getReferenceTo(mViewNew, entity); // create View Reference
ViewReference viewRef = dmFactoryImpl.init().createViewReference();
viewRef.setReferenceType(ReferenceType.ENTITY);
viewRef.setParentView(mViewNew);
viewRef.setEntityId(entity.getUID());
ViewReferenceUtil.setViewReferenceDefaultRefAlias(viewRef, mContainer);
mViewNew.getViewReferenceList().add(viewRef); // create View Column list
for (int j = 0; j < mVLList.getSelectionIndices().length; j++) {
int indexColumn = mVLList.getSelectionIndices()[j];
Column column = totalColumnList.get(indexColumn);
if (column.getParentEntity() == entity) {
ViewColumn viewCol = dmFactoryImpl.init().createViewColumn();
viewCol.setViewReference(viewRef);
ViewColumnUtil.setViewColumnDefaultValue(viewCol, column);
mViewNew.getViewColumnList().add(viewCol);
}
}
}
} protected void okPressed() {
makeViewReferenceList();
super.okPressed();
}
}
你报了什么异常?
at org.eclipse.swt.SWT.error(SWT.java:3374)
at org.eclipse.swt.SWT.error(SWT.java:3297)
at org.eclipse.swt.SWT.error(SWT.java:3268)
at org.eclipse.swt.widgets.Widget.error(Widget.java:435)
at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:331)
at org.eclipse.swt.widgets.List.add(List.java:94)
at COM.serialEvent(COM.java:256)
at com.sun.comm.Win32SerialPort.sendDataAvailEvent(Win32SerialPort.java:649)
at com.sun.comm.NotificationThread.run(Win32SerialPort.java:878)
Display.getDefault().asyncExec(new Runnable(){ @Override
public void run() {
mVRList.add("1235");
}});
试试呢,一般这个错误都是因为非界面线程操作界面引起的