我正在使用controlsfx ToggleSwitch来模拟串行端口连接的开/关按钮。问题是当我试图打开一个已经在使用中的端口时。我将其设置为false,这将再次触发该事件。所以它调用不同的if块。它会自我循环,然后从头开始。你知道我怎么才能克服这个问题吗?谢谢。
portSwitch.selectedProperty().addListener(((observable, oldValue, newValue) -> {
if (newValue) {// try to connect to the port
openPort=port.open();
if (openPort) {
portSwitch.selectedProperty().set(true);//enable the switch
} else {
portSwitch.selectedProperty().set(false);//port is already in use. turn off the switch
}
} else {//disconnecting from the port
if(!port.isOpen()) //if the port is succelly closed
{
portSwitch.selectedProperty().set(false);//turn off the switch
}else{//Could not close the port.
portSwitch.selectedProperty().set(true);//So let the switch stay on
}
}
}));发布于 2018-08-08 22:09:31
谢谢你们的回答伙计们。但是我已经编写了我的自定义开关并应用了下面的逻辑。如果需要的话,我可以把它贴出来。
void connectionListener() {
connectionButton.switchedOnProperty().addListener((obs, oldState, newState) -> {
final boolean oldConnectionStatus = port.isOpen();
final boolean isOn = newState.booleanValue();
if (isOn) {
//Logic
changeSwitchStatus(isOn, oldConnectionStatus));
} else {
//logic
changeSwitchStatus(isOn, oldConnectionStatus));
}
});
}
private void changeSwitchStatus(boolean newStatus, boolean oldConnectionStatus) {
final boolean newConnectionStatus = port.isOpen();
if (!oldConnectionStatus) {
if (newConnectionStatus && newStatus) {
//logic
connectionButton.turnOn();
}
if (!newConnectionStatus && newStatus) {
//logic
connectionButton.turnOff();
}
} else {
if (!newConnectionStatus && !newStatus) {
//logic
connectionButton.turnOff();
}
if (newConnectionStatus && !newStatus) {
//logic
connectionButton.turnOn();
}
}
}https://stackoverflow.com/questions/51736405
复制相似问题