JavaFx ToggleSwitch开启关闭同步

时间:2018-08-07 22:45:03

标签: java javafx javafx-8 controlsfx

我正在使用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 
            }
        }
    }));

1 个答案:

答案 0 :(得分:0)

谢谢大家的回答。但是我已经编写了自定义开关并应用了以下逻辑。我可以根据需要发布它。

 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();
        }
    }
}