我尝试实现与此类似的 JavaFX EventFilter
:
@FXML
public void leftButton() {
leftButton.addEventFilter(MouseEvent.MOUSE_PRESSED,
new EventHandler < MouseEvent > () {
@Override
public void handle(MouseEvent event) {
try {
System.out.println("Left Button pressed, String: " + leftString);
byte[] command = {
(byte) startTx, address, byteOne, panLeft, speedNormal, 0x00, endTx, 0x2B
};
//byte[] bytes = DatatypeConverter.parseHexBinary(upString);
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
twoWaySerCom.serialPort.getOutputStream());
sw.out.write(command);
} catch (IOException e) {
e.printStackTrace();
}
}
});
leftButton.addEventFilter(MouseEvent.MOUSE_RELEASED,
new EventHandler < MouseEvent > () {
public void handle(MouseEvent event) {
try {
System.out.println("Left Button released, String: " + stopString);
byte[] command = {
(byte) startTx, address, byteOne, 0x00, 0x00, 0x00, (byte) endTx, 0x0F
};
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
twoWaySerCom.serialPort.getOutputStream());
sw.out.write(command);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
这样,当单击 Button
时,我通过串行端口写入一个字符串,当我释放 Button
时,会发送一个不同的字符串。
我有两个问题
1. 当我第一次打开应用程序时,我必须按 Button
两次才能发生任何事情
2. 每额外点击一次,该操作就会再次发生。 EG 第一次点击“HELLO” 第二次点击“HELLO HELLO”
我怀疑我的问题是我的第一次单击注册了 EventFilter
,然后每个后续事件都会创建一个新的 EventFilter
如何防止这种情况发生?
最佳答案
- when I first open the application, I have to press the Button twice before anything happens
您可以在方法 leftButton()
中添加事件过滤器,该方法会在按钮操作时调用。因此,当您第一次单击按钮时,没有附加任何事件过滤器,因此什么也不会发生。
要克服这个问题,您可以将代码移至 initialize()
或使用单独的方法来放置这些代码,然后使用 FXML 调用它们。
新闻报道
public void onPress() {
try {
System.out.println("Left Button pressed, String: " + leftString);
byte[] command = { (byte) startTx, address, byteOne, panLeft, speedNormal, 0x00, endTx, 0x2B };
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
twoWaySerCom.serialPort.getOutputStream());
sw.out.write(command);
} catch (IOException e) {
e.printStackTrace();
}
}
发布时
public void onRelease() {
try {
System.out.println("Left Button released, String: " + stopString);
byte[] command = {(byte) startTx, address, byteOne, 0x00, 0x00, 0x00, (byte) endTx, 0x0F};
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(twoWaySerCom.serialPort.getOutputStream());
sw.out.write(command);
} catch (IOException e) {
e.printStackTrace();
}
}
FXML
<Button id="leftButton" fx:id="leftButton" onMousePressed="#onPress" onMouseReleased="#onRelease"/>
- for every additional click the action happens again. EG first click "HELLO" Second click "HELLO HELLO"
尽管我不确定,但您似乎正在写入同一个流,因此附加了您的数据。
关于JavaFX 事件过滤器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38911990/