我已经尝试实现了类似下面这样的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.每多点击一次,动作就会再次发生。例如,第一次点击"HELLO“,第二次点击" HELLO”
我怀疑我的问题是第一次单击注册了EventFilter,然后每个后续事件都创建了一个新的EventFilter
如何防止这种情况发生?
发布于 2016-08-12 16:04:05
您可以在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();
}
}Release上的
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"/>虽然,我不确定,但您似乎正在写入相同的流,因此附加您的数据。
发布于 2016-08-12 16:10:25
如果您确实需要event filters,则需要将leftButton()方法中的代码移动到initialize方法中。否则,该方法将在每次调用时添加额外的侦听器。
@FXML
private initialize() {
leftButton.addEventFilter(MouseEvent.MOUSE_PRESSED,
...
);
leftButton.addEventFilter(MouseEvent.MOUSE_RELEASED,
...
);
}如果事件处理程序足够,则创建2个处理程序,并从fxml中注册它们:
@FXML
private void leftButtonPressed() {
...
}
@FXML
private void leftButtonReleased() {
...
}<Button fx:id="leftButton" onMousePressed="#leftButtonPressed" onMouseReleased="#leftButtonReleased"https://stackoverflow.com/questions/38911990
复制相似问题