【问题标题】:JavaFx ToggleSwitch On Off SyncronizationJavaFx 切换开关同步
【发布时间】:2018-08-07 22:45:03
【问题描述】:

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

【问题讨论】:

  • 我要告诉你,你可能不应该手动设置selectedProperty
  • 如果连接不成功,我想不出另一种方法来关闭它。

标签: java javafx javafx-8 controlsfx


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多