1

I am using controlsfx ToggleSwitch to simulate an on/off button for serial port connection. The problem is when I try to open a port that is already in use. I set it to false and this triggers the event again. So it calls different if block. It loops itself and starts all over again. Any idea how I can overcome this? Thanks.

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 
            }
        }
    }));
anupampunith
  • 147
  • 4
  • 12

1 Answers1

0

Thanks for the answers guys. But I have wrote my custom switch and applied the logic below. I can post it if needed.

 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();
        }
    }
}
anupampunith
  • 147
  • 4
  • 12