我写了一个名为 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/