Java程序报错。关键字:swt,事件监听,串口通讯。
出错部分已用中文标出,请高手帮忙指导。出错程序源码:package com.xuchenguang;import java.io.*;
import javax.comm.*;import org.eclipse.swt.widgets.Text; public class SerialBean implements SerialPortEventListener
{ protected SerialPort serialPort;
private static String PortName;
private static OutputStream out;
private static InputStream in;
private CommPortIdentifier portId;
private BufferedInputStream reader;
private String ReadString;
private int numBytes=0;
private Text t1; public SerialBean(int PortID,Text t1) {
PortName="COM"+PortID;
this.t1=t1;
this.t1.append("IIIIIIIIIIIIIIIIIIIIIIIIIII");
}
public void myid(){
System.out.println("aaa");
}
public boolean Initialize(){
boolean InitSuccess=true;
boolean InitFail=false;
try{
portId=CommPortIdentifier.getPortIdentifier(PortName);
try{
serialPort=(SerialPort)portId.open("Serial_Communication", 2000);
}catch(PortInUseException e){
return InitFail;
}
try{
in=serialPort.getInputStream();
reader=new BufferedInputStream(in);
out=serialPort.getOutputStream();
}catch (IOException e){
return InitFail;
}
try{
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
}catch(UnsupportedCommOperationException e){
return InitFail;
}
}catch (NoSuchPortException e){
return InitFail;
}
return InitSuccess;
}
public void ReadPort(){
try{
serialPort.addEventListener(this);
}catch(Exception e){}
serialPort.notifyOnDataAvailable(true);
}
public void StopRead(){
try{
serialPort.removeEventListener();
}catch(Exception e){}
serialPort.notifyOnDataAvailable(false);
}
public void WritePort(String Msg){
try{
for(int i=0;i<Msg.length();i++)
out.write(Msg.charAt(i));
}catch(IOException e){
}
}
public void ClosePort(){
serialPort.close();
}
public void serialEvent(SerialPortEvent event) {
byte[] readBuffer=new byte[200];
if(event.getEventType()==SerialPortEvent.DATA_AVAILABLE){
try {
while (in.available() > 0) {
numBytes = reader.read(readBuffer);
}
ReadString+= new String(readBuffer,0,numBytes);
System.out.println(ReadString);
t1.append(ReadString);//就是这里出错了。把它注释掉就好了,但是我想实现在t1这个Text上显示接收到的信息,高手指导一下。
}catch (IOException e) {System.err.println(e);}
}
}
}
出错部分已用中文标出,请高手帮忙指导。出错程序源码:package com.xuchenguang;import java.io.*;
import javax.comm.*;import org.eclipse.swt.widgets.Text; public class SerialBean implements SerialPortEventListener
{ protected SerialPort serialPort;
private static String PortName;
private static OutputStream out;
private static InputStream in;
private CommPortIdentifier portId;
private BufferedInputStream reader;
private String ReadString;
private int numBytes=0;
private Text t1; public SerialBean(int PortID,Text t1) {
PortName="COM"+PortID;
this.t1=t1;
this.t1.append("IIIIIIIIIIIIIIIIIIIIIIIIIII");
}
public void myid(){
System.out.println("aaa");
}
public boolean Initialize(){
boolean InitSuccess=true;
boolean InitFail=false;
try{
portId=CommPortIdentifier.getPortIdentifier(PortName);
try{
serialPort=(SerialPort)portId.open("Serial_Communication", 2000);
}catch(PortInUseException e){
return InitFail;
}
try{
in=serialPort.getInputStream();
reader=new BufferedInputStream(in);
out=serialPort.getOutputStream();
}catch (IOException e){
return InitFail;
}
try{
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
}catch(UnsupportedCommOperationException e){
return InitFail;
}
}catch (NoSuchPortException e){
return InitFail;
}
return InitSuccess;
}
public void ReadPort(){
try{
serialPort.addEventListener(this);
}catch(Exception e){}
serialPort.notifyOnDataAvailable(true);
}
public void StopRead(){
try{
serialPort.removeEventListener();
}catch(Exception e){}
serialPort.notifyOnDataAvailable(false);
}
public void WritePort(String Msg){
try{
for(int i=0;i<Msg.length();i++)
out.write(Msg.charAt(i));
}catch(IOException e){
}
}
public void ClosePort(){
serialPort.close();
}
public void serialEvent(SerialPortEvent event) {
byte[] readBuffer=new byte[200];
if(event.getEventType()==SerialPortEvent.DATA_AVAILABLE){
try {
while (in.available() > 0) {
numBytes = reader.read(readBuffer);
}
ReadString+= new String(readBuffer,0,numBytes);
System.out.println(ReadString);
t1.append(ReadString);//就是这里出错了。把它注释掉就好了,但是我想实现在t1这个Text上显示接收到的信息,高手指导一下。
}catch (IOException e) {System.err.println(e);}
}
}
}
解决方案 »
- 两个简单问题先来先给分[网络 + string]
- 判断字符串中是否含某个字符,提示了java.lang.NullPointerException
- 请问:java -jar app.jar 可以运行,双击却不能(could not find the main class。。。),为啥?
- java笔试中的数据库题目
- 北京XX公司(广州分公司)笔试题
- 大拿快帮忙--Java如何将unicode转换为UTF8
- 百分求助,在线等待:读写该件高手帮助!多谢!!!!
- 如果想把一个很大的文件,分块读取,应该怎样实现?(在线等待)
- 请问将货币类型数据从access数据库取出来变成双精度类型的该怎么办?将双精度类型又如何变成货币类型放进数据库呢?
- 请各位高手指教!急!
- jScrollPanel.getViewport().add(tree,null)
- 如何根据日期获取log4j的日志文件名?
其它相关部分:
package com.xuchenguang;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;public class SeaLightMIS { /**
* Launch the application
* @param args
*/
public static void main(String[] args) {
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(476, 131);
shell.setText("管理信息系统");
//
shell.open(); final Button button = new Button(shell, SWT.NONE);
button.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE));
button.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
new ComReceive();
}
});
button.setText("监测");
button.setBounds(10, 10, 96, 82); final Button button_1 = new Button(shell, SWT.NONE);
button_1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
new DynamicCmp();
}
});
button_1.setText("分析");
button_1.setBounds(128, 9, 102, 83);
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
package com.xuchenguang;import java.util.Properties;import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import com.swtdesigner.SWTResourceManager;public class ComReceive {
private Text output_text;
// private static String input_string=null;
// private static String LS_monitor;
private static int li_port_in; private Text input_text;
SerialBean SB;
Properties pp = System.getProperties();
String newLine = pp.getProperty("line.separator"); public ComReceive() {
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(574, 375);
shell.setText("数据采集");
//
shell.open(); final Button button_open = new Button(shell, SWT.NONE);
button_open.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
// System.out.println(li_port_in);
SB = new SerialBean(li_port_in,input_text);
SB.Initialize();
}
});
button_open.setText("打开端口");
button_open.setBounds(481, 70, 75, 23); input_text = new Text(shell, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER);
input_text.setTextLimit(50000);
input_text.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GREEN));
input_text.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
input_text.setBounds(5, 5, 464, 159); final Label label = new Label(shell, SWT.NONE);
label.setText("端口:");
label.setBounds(481, 37, 36, 13); final Spinner port_in = new Spinner(shell, SWT.BORDER);
port_in.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent arg0) {
li_port_in = port_in.getSelection();
}
});
port_in.setMinimum(4);
port_in.setBounds(521, 32, 35, 23); final Button button_read = new Button(shell, SWT.NONE);
button_read.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
SB.ReadPort();
// input_text.append(SB.ReadString);
input_text.append("aaaaaaaaa\r\n");
// }
}
});
button_read.setBounds(481, 119, 75, 23);
button_read.setText("开始监听"); final Button button_close = new Button(shell, SWT.NONE);
button_close.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
SB.ClosePort();
}
});
button_close.setBounds(481, 213, 75, 23);
button_close.setText("关闭端口"); final Button button_writer = new Button(shell, SWT.NONE);
button_writer.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
SB.WritePort(output_text.getText());
}
});
button_writer.setBounds(481, 168, 75, 23);
button_writer.setText("写入数据"); output_text = new Text(shell, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER);
output_text.setBounds(5, 170, 464, 159);
output_text.setTextLimit(50000);
output_text.setForeground(SWTResourceManager.getColor(0, 255, 0));
output_text.setBackground(SWTResourceManager.getColor(0, 0, 0));
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}================================结束============================================
gui这一块不熟悉,保什么错误呢?
另外,
我的出错信息如下: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.Text.append(Text.java:241)
at com.xuchenguang.SerialBean.serialEvent(SerialBean.java:91)
at com.sun.comm.Win32SerialPort.sendDataAvailEvent(Win32SerialPort.java:649)
at com.sun.comm.NotificationThread.run(Win32SerialPort.java:878)
SWT中要用Display.getDefault().asyncExec()启动一个线程去刷新UI......
t1.append(ReadString);//就是这里出错了。把它注释掉就好
----------------------------------------------------------
改為:
Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
t1.append(ReadString);//
//shell.redraw();
}
});
一个被称为用户界面线程的单一的重要线程负责处理事件,调度它们到合适的窗口小部件,以及进行窗体描绘。没有了它,你的程序将无法做任何事情。你可能认为我们过去说过一些这方面的内容,我们的确曾经说过。
在AWT和Swing中,用户界面线程或事件处理线程对开发者是隐藏的。而在SWT中,创建消息泵的线程就成了用户界面线程。这个设计决定使得要将SWT插件插入Eclipse中变得可能。与Sun的方法背离的另一点是,SWT的设计允许拥有多于一个的事件调度线程。(这个功能极少用到,我们提到它只是为了完整起见。)
主线程就是用户界面线程,所以你不该执行任何复杂的或耗时的任务(如数据库访问)或者其他会阻塞线程的任务。相反的,你应该转到其他线程去执行那些操作。不这么做的话,将会严重影响你的用户界面的响应能力并且会给用户带来不便,这永远不是件好事。与此相关的事实就是,唯一允许调用SWT窗口小部件而不会引发SWTException异常的线程就是用户界面线程。
你也许想知道在你转到的线程完成之后如何更新用户界面。要做到这样,你要使用两个辅助方法,它们是显示类(Display)的一部分:asyncExec()和syncExec()。(Swing用户注意:这些方法和Swing工具包类中的invokeLater()和invokeAndWait()方法同义。并且,是的,如果你觉得Sun的方法的命名更为清晰,我们赞同。)这些方法按以下方式工作:
asyncExec(Runnable)--当你需要更新用户界面但并不关心具体何时更新时使用。记住,使用此方法意味着后台线程和用户界面间的处理不存在任何可保证的关联。
syncExec(Runnable)--当你的背景线程需要先进行用户界面更新才能继续处理时使用。注意,在用户界面更新进行之前,你的背景线程会被阻塞。
这些方法都采取了实现Runnable接口的类。以下代码显示了你一般会如何使用这些方法: Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
button.setText(new Date().toString());
}
});
asyncExec()方法是显示类的一部分,所以你首先需要取得显示类的当前实例,这样做就避免了在你的整个程序中传递显示类的引用。你将一个实现了Runnable接口的类传递到asyncExec()方法。通常你创建一个匿名类来进行更新,正如前面的例子所示。
D.5 构建和运行SWT程序
package com.xuchenguang;import java.util.Properties;import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import com.swtdesigner.SWTResourceManager;public class ComReceive {
private Text output_text;
// private static String input_string=null;
// private static String LS_monitor;
private static int li_port_in; private Text input_text;
SerialBean SB; Properties pp = System.getProperties();
String newLine = pp.getProperty("line.separator"); public ComReceive() {
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(574, 375);
shell.setText("数据采集");
//
shell.open(); final Button button_open = new Button(shell, SWT.NONE);
button_open.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
// System.out.println(li_port_in);
SB = new SerialBean(li_port_in,input_text,display);
SB.Initialize();
}
});
button_open.setText("打开端口");
button_open.setBounds(481, 70, 75, 23); input_text = new Text(shell, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER);
input_text.setTextLimit(50000);
input_text.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GREEN));
input_text.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
input_text.setBounds(5, 5, 464, 159); final Label label = new Label(shell, SWT.NONE);
label.setText("端口:");
label.setBounds(481, 37, 36, 13); final Spinner port_in = new Spinner(shell, SWT.BORDER);
port_in.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent arg0) {
li_port_in = port_in.getSelection();
}
});
port_in.setMinimum(4);
port_in.setBounds(521, 32, 35, 23); final Button button_read = new Button(shell, SWT.NONE);
button_read.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
SB.ReadPort();
// input_text.append(SB.ReadString);
input_text.append("aaaaaaaaa\r\n");
// }
}
});
button_read.setBounds(481, 119, 75, 23);
button_read.setText("开始监听"); final Button button_close = new Button(shell, SWT.NONE);
button_close.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
SB.ClosePort();
}
});
button_close.setBounds(481, 213, 75, 23);
button_close.setText("关闭端口"); final Button button_writer = new Button(shell, SWT.NONE);
button_writer.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
SB.WritePort(output_text.getText());
}
});
button_writer.setBounds(481, 168, 75, 23);
button_writer.setText("写入数据"); output_text = new Text(shell, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER);
output_text.setBounds(5, 170, 464, 159);
output_text.setTextLimit(50000);
output_text.setForeground(SWTResourceManager.getColor(0, 255, 0));
output_text.setBackground(SWTResourceManager.getColor(0, 0, 0));
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
import javax.comm.*;import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text; public class SerialBean implements SerialPortEventListener
{ protected SerialPort serialPort;
private static String PortName;
private static OutputStream out;
private static InputStream in;
private CommPortIdentifier portId;
private BufferedInputStream reader;
private String ReadString;
private int numBytes=0;
private Text t1;
private Display display; public SerialBean(int PortID,Text t1,Display display) {
PortName="COM"+PortID;
this.t1=t1;
this.display = display;
this.t1.append("IIIIIIIIIIIIIIIIIIIIIIIIIII");
}
public void myid(){
System.out.println("aaa");
}
public boolean Initialize(){
boolean InitSuccess=true;
boolean InitFail=false;
try{
portId=CommPortIdentifier.getPortIdentifier(PortName);
try{
serialPort=(SerialPort)portId.open("Serial_Communication", 2000);
}catch(PortInUseException e){
return InitFail;
}
try{
in=serialPort.getInputStream();
reader=new BufferedInputStream(in);
out=serialPort.getOutputStream();
}catch (IOException e){
return InitFail;
}
try{
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
}catch(UnsupportedCommOperationException e){
return InitFail;
}
}catch (NoSuchPortException e){
return InitFail;
}
return InitSuccess;
}
public void ReadPort(){
try{
serialPort.addEventListener(this);
}catch(Exception e){}
serialPort.notifyOnDataAvailable(true);
}
public void StopRead(){
try{
serialPort.removeEventListener();
}catch(Exception e){}
serialPort.notifyOnDataAvailable(false);
}
public void WritePort(String Msg){
try{
for(int i=0;i<Msg.length();i++)
out.write(Msg.charAt(i));
}catch(IOException e){
}
}
public void ClosePort(){
serialPort.close();
}
public void serialEvent(SerialPortEvent event) {
byte[] readBuffer=new byte[200];
if(event.getEventType()==SerialPortEvent.DATA_AVAILABLE){
try {
while (in.available() > 0) {
numBytes = reader.read(readBuffer);
}
ReadString+= new String(readBuffer,0,numBytes);
System.out.println(ReadString); display.asyncExec(new Runnable() {
public void run() {
t1.append(ReadString);
}
});
// t1.append(ReadString); //就是这里出错了。把它注释掉就好了,但是我想实现在t1这个Text上显示接收到的信息,高手指导一下。
}catch (IOException e) {System.err.println(e);}
}
}
}