java - 重写serialEvent两次

标签 java serial-port overriding arduino

我写了一个名为 ArduinoSerial 的类实现 SerialPortEventListener .

我使用此类作为库,将其导入到另一个名为 ArduinoGUI 的程序中,这会创建一个包含一系列复选框的 swing GUI。

当我想写入串行端口时,我有一个私有(private)成员变量 ArduinoGUI私有(private)类(class)ArduinoSerial Arduino;

我调用arduino.output.write(byte b);功能并且工作正常。

问题在于内部 ArduinoSerial类重写了读取函数,并且当前将输出吐出到 system.out。

    @Override
public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine=input.readLine();
            System.out.println(inputLine);

        } catch (Exception e) {
            System.err.println(e.toString());
                            System.out.println("But nothing much to worry about.");
        }
    }
    // Ignore all the other eventTypes, but you should consider the other ones.
}

但这不是我想要的,但是我想将串行数据读入 ArduinoGUI 内的字节数组中类,但我不确定如何在获取 ArduinoSerial 时再次重写此方法和/或为串行端口上的数据编写事件监听器类首先不读取并丢弃缓冲区。

最佳答案

是的,你不能重写方法两次,但你可以做以下事情:

public class ArduinoGUI extends JFrame implements ArduinoSerialItf { 

private ArduinoSerialItf arduinoSerialItf = null; 
private ArduinoSerial arduinoSerial = null;

 //init 
 public ArduinoGUI(){
    arduinoSerialItf = this;

   arduinoSerial = new ArduinoSerial(arduinoSerialItf );

 } 

@Override
public void onEventReceived(SerialPortEvent oEvent){
   // in GUI class you get event from ArduinoSerial 
}

}    

创建接口(interface):

public interface ArduinoSerialItf {
 public void onEventReceived(SerialPortEvent oEvent);
}

Arduino串行类:

public class ArduinoSerial implements SerialPortEventListener {

private ArduinoSerialItf arduinoSerialItf = null;

public ArduinoSerial(ArduinoSerialItf arduinoSerialItf){
  this.arduinoSerialItf = arduinoSerialItf;
} 

@Override
public synchronized void serialEvent(SerialPortEvent oEvent) {
    // when we call this method, event goes to GUI class
    arduinoSerialItf.onEventReceived(oEvent);

}

关于java - 重写serialEvent两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15502044/

相关文章:

asp.net - 覆盖用户控件中的方法

java - 调用包存储过程时超出了最大游标数

Java小程序在IDE中连接mysql,但在浏览器中连接失败

java - Spring MVC : How to call @Service class from another project

java - 比较用于绘制网络拓扑的开源 Java 图形绘制框架(JUNG 和 Prefuse)

c++ - 如何从字节流中提取数据包?

c++ - Qt QextSerialPort 静态库

.net - 串口电缆拔出

传递父类(super class)型的 Java 接口(interface)方法

c++ - 如果我要覆盖它,我可以调用基类的虚函数吗?