javafx.beans.binding.BooleanBinding Java Examples

The following examples show how to use javafx.beans.binding.BooleanBinding. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TrainingPane.java    From OpenLabeler with Apache License 2.0 6 votes vote down vote up
private void bindProperties() {
    // Update on any directory changes
    dirTFImage.textProperty().addListener((observable, oldValue, newValue) -> updateNumSamples());
    dirTFAnnotation.textProperty().addListener((observable, oldValue, newValue) -> updateNumSamples());
    dirTFData.textProperty().addListener((observable, oldValue, newValue) -> updateLabelMap());
    dirTFBaseModel.textProperty().addListener((observable, oldValue, newValue) -> updateTraining());

    BooleanBinding changes[] = {
            dirTFImage.textProperty().isNotEqualTo(Settings.tfImageDirProperty),
            dirTFAnnotation.textProperty().isNotEqualTo(Settings.tfAnnotationDirProperty),
            dirTFData.textProperty().isNotEqualTo(Settings.tfDataDirProperty),
            new SimpleListProperty(labelMapPane.getItems()).isNotEqualTo(
                    FXCollections.observableList(TFTrainer.getLabelMapItems(dirTFData.getText()))),
            dirTFBaseModel.textProperty().isNotEqualTo(Settings.tfBaseModelDirProperty),
            txtDockerImage.textProperty().isNotEqualTo(Settings.dockerImageProperty),
            txtContainerHostName.textProperty().isNotEqualTo(Settings.containerHostNameProperty),
            txtContainerName.textProperty().isNotEqualTo(Settings.containerNameProperty),
    };
    dirtyProperty.unbind();
    dirtyProperty.bind(EasyBind.combine(
            FXCollections.observableArrayList(changes), stream -> stream.reduce((a, b) -> a | b).orElse(false)));
}
 
Example #2
Source File: IncorrectMatchPresenter.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void initialize() {

        incorrectView.setShowTransitionFactory(FlipInYTransition::new);

        toggleGroup.selectToggle(null);

        BooleanBinding toggleNotSelected = Bindings.createBooleanBinding(
                () -> toggleGroup.getSelectedToggle() == null,
                toggleGroup.selectedToggleProperty()
        );
        submitButton.disableProperty().bind(toggleNotSelected);
     //   imageView.imageProperty().bind(model.filteredImageProperty());
        incorrectView.showingProperty().addListener((obs, oldValue, newValue) -> {
            if (newValue) {
                AppBar appBar = getApp().getAppBar();
                appBar.setTitleText("Incorrect Match");
                appBar.setNavIcon(MaterialDesignIcon.ERROR.button());
            }
        });
    }
 
Example #3
Source File: MainView.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void updateHost() {

        Dialog<String> dialog = new Dialog<String>("Host", null);

        TextField hostField = new TextField(TicTacToe.getHost());
        dialog.setContent(hostField);

        Button okButton = new Button("OK");
        okButton.setOnAction(e -> {
            dialog.setResult(hostField.getText());
            dialog.hide();
        });

        BooleanBinding urlBinding = Bindings.createBooleanBinding(
                () -> isUrlValid(hostField.getText()),
                hostField.textProperty());
        okButton.disableProperty().bind(urlBinding.not());

        Button cancelButton = new Button("CANCEL");
        cancelButton.setOnAction(e -> dialog.hide());
        dialog.getButtons().addAll(okButton,cancelButton);
        dialog.showAndWait().ifPresent( url -> TicTacToe.setHost(url));

    }
 
Example #4
Source File: WordStateHandler.java    From VocabHunter with Apache License 2.0 6 votes vote down vote up
public void initialise(final Button buttonUnseen, final Button buttonKnown, final Button buttonUnknown, final SessionModel sessionModel,
                        final ObjectBinding<WordState> wordStateProperty, final Runnable nextWordSelector) {
    this.sessionModel = sessionModel;
    this.nextWordSelector = nextWordSelector;

    SimpleBooleanProperty editableProperty = sessionModel.editableProperty();
    BooleanBinding resettableProperty = editableProperty.and(notEqual(WordState.UNSEEN, wordStateProperty));

    buttonUnseen.visibleProperty().bind(resettableProperty);
    buttonKnown.visibleProperty().bind(editableProperty);
    buttonUnknown.visibleProperty().bind(editableProperty);

    buttonUnseen.setOnAction(e -> processResponse(WordState.UNSEEN, false));
    buttonKnown.setOnAction(e -> processResponse(WordState.KNOWN, true));
    buttonUnknown.setOnAction(e -> processResponse(WordState.UNKNOWN, true));
}
 
Example #5
Source File: PasswordDialogController.java    From chvote-1-0 with GNU Affero General Public License v3.0 6 votes vote down vote up
private BooleanBinding bindForValidity(boolean withConfirmation, TextField electionOfficer1Password, TextField electionOfficer2Password, Label errorMessage, Node confirmButton) {
    BooleanBinding passwordsValid = Bindings.createBooleanBinding(
            () -> withConfirmation ? arePasswordsEqualAndValid(electionOfficer1Password.textProperty(), electionOfficer2Password.textProperty()) : isPasswordValid(electionOfficer1Password.getText()),
            electionOfficer1Password.textProperty(),
            electionOfficer2Password.textProperty());
    passwordsValid.addListener((observable, werePasswordsValid, arePasswordsValid) -> {
        confirmButton.setDisable(!arePasswordsValid);
        errorMessage.setVisible(!arePasswordsValid && withConfirmation);
    });
    return passwordsValid;
}
 
Example #6
Source File: VirtualAssetEditorDialog.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
@Override
@FxThread
protected @NotNull ObservableBooleanValue buildAdditionalDisableCondition() {

    final VirtualResourceTree<C> resourceTree = getResourceTree();
    final MultipleSelectionModel<TreeItem<VirtualResourceElement<?>>> selectionModel = resourceTree.getSelectionModel();
    final ReadOnlyObjectProperty<TreeItem<VirtualResourceElement<?>>> selectedItemProperty = selectionModel.selectedItemProperty();

    final Class<C> type = getObjectsType();
    final BooleanBinding typeCondition = new BooleanBinding() {

        @Override
        protected boolean computeValue() {
            final TreeItem<VirtualResourceElement<?>> treeItem = selectedItemProperty.get();
            return treeItem == null || !type.isInstance(treeItem.getValue().getObject());
        }

        @Override
        public Boolean getValue() {
            return computeValue();
        }
    };

    return Bindings.or(selectedItemProperty.isNull(), typeCondition);
}
 
Example #7
Source File: InferencePane.java    From OpenLabeler with Apache License 2.0 6 votes vote down vote up
public InferencePane() {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/preference/InferencePane.fxml"), bundle);
    loader.setRoot(this);
    loader.setController(this);

    try {
        loader.load();
    }
    catch (Exception ex) {
        LOG.log(Level.SEVERE, "Unable to load FXML", ex);
    }

    // Bind Properties
    BooleanBinding changes[] = {
            chkUseInference.selectedProperty().isNotEqualTo(Settings.useInferenceProperty),
            pickerHintStrokeColor.valueProperty().isNotEqualTo(Settings.hintStrokeColorProperty),
            fileTFLabelMap.textProperty().isNotEqualTo(Settings.tfLabelMapFileProperty),
            dirTFSavedModel.textProperty().isNotEqualTo(Settings.tfSavedModelDirProperty),
    };
    dirtyProperty.bind(EasyBind.combine(
            FXCollections.observableArrayList(changes), stream -> stream.reduce((a, b) -> a | b).orElse(false)));

    load();
}
 
Example #8
Source File: Network.java    From PeerWasp with MIT License 5 votes vote down vote up
@Override
public void initialize(URL location, ResourceBundle resources) {
	lwBootstrappingNodes.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

	addresses = lwBootstrappingNodes.getItems();

	// disable buttons if no item selected
	BooleanBinding isNoItemSelected = lwBootstrappingNodes.getSelectionModel().selectedItemProperty().isNull();
	btnEdit.disableProperty().bind(isNoItemSelected);
	btnRemove.disableProperty().bind(isNoItemSelected);
	btnUp.disableProperty().bind(isNoItemSelected);
	btnDown.disableProperty().bind(isNoItemSelected);

	reset();
}
 
Example #9
Source File: GeneralPane.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
public GeneralPane() {
   FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/preference/GeneralPane.fxml"), bundle);
   loader.setRoot(this);
   loader.setController(this);

   try {
      loader.load();
   }
   catch (Exception ex) {
      LOG.log(Level.SEVERE, "Unable to load FXML", ex);
   }

   // Bind Properties
   BooleanBinding changes[] = {
         chkOpenLastMedia.selectedProperty().isNotEqualTo(Settings.openLastMediaProperty),
         chkSaveEveryChange.selectedProperty().isNotEqualTo(Settings.saveEveryChangeProperty),
         textAnnotationsDir.textProperty().isNotEqualTo(Settings.annotationDirProperty),
         pickerObjectStrokeColor.valueProperty().isNotEqualTo(Settings.objectStrokeColorProperty),
         chkAutoSetName.selectedProperty().isNotEqualTo(Settings.autoSetNameProperty),
         chkAnimateOutline.selectedProperty().isNotEqualTo(Settings.animateOutlineProperty),
         new SimpleListProperty(nameTablePane.getItems()).isNotEqualTo(Settings.recentNamesProperty),
   };
   dirtyProperty.bind(EasyBind.combine(
         FXCollections.observableArrayList(changes), stream -> stream.reduce((a, b) -> a | b).orElse(false)));

   load();
}
 
Example #10
Source File: AboutPanelSkin.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates the {@link Hyperlink} leading to the git revision on github
 *
 * @return The {@link Hyperlink} leading to the git revision on github
 */
private Hyperlink createGitRevisionHyperlink() {
    final StringBinding revisionText = Bindings.createStringBinding(
            () -> Optional.ofNullable(getControl().getBuildInformation())
                    .map(ApplicationBuildInformation::getApplicationGitRevision).orElse(null),
            getControl().buildInformationProperty());

    final BooleanBinding disableProperty = Bindings.when(Bindings
            .and(Bindings.isNotNull(revisionText), Bindings.notEqual(revisionText, "unknown")))
            .then(false).otherwise(true);

    final Hyperlink gitRevisionHyperlink = new Hyperlink();

    gitRevisionHyperlink.textProperty().bind(revisionText);

    // if the git revision equals "unknown" disable the hyperlink
    gitRevisionHyperlink.disableProperty().bind(disableProperty);
    gitRevisionHyperlink.visitedProperty().bind(disableProperty);
    gitRevisionHyperlink.underlineProperty().bind(disableProperty);

    // if the git revision has been clicked on open the corresponding commit page on github
    gitRevisionHyperlink.setOnAction(event -> {
        try {
            final URI uri = new URI("https://github.com/PhoenicisOrg/phoenicis/commit/"
                    + getControl().getBuildInformation().getApplicationGitRevision());

            getControl().getOpener().open(uri);
        } catch (URISyntaxException e) {
            LOGGER.error("Could not open GitHub URL.", e);
        }
    });

    return gitRevisionHyperlink;
}
 
Example #11
Source File: KeyTestingController.java    From chvote-1-0 with GNU Affero General Public License v3.0 5 votes vote down vote up
private void initializeBindings() {
    encryptButton.setDisable(true);
    BooleanBinding plainTextsEmpty = Bindings.createBooleanBinding(plainTexts::isEmpty, plainTexts);
    plainTextsEmpty.addListener(
            (observable, oldValue, isPlainTextListEmpty) ->
                    encryptButton.setDisable(isPlainTextListEmpty)
    );

    decryptButton.setDisable(true);
    cipherTexts.addListener((ListChangeListener<AuthenticatedBallot>) c -> decryptButton.setDisable(c.getList().isEmpty()));
}
 
Example #12
Source File: ListenerConfigView.java    From kafka-message-tool with MIT License 5 votes vote down vote up
private void configureGuiControlDisableStateBasedOnStartButtonState() {
    final BooleanBinding disabledProperty = stopButton.disableProperty().not();
    consumerGroupTextField.disableProperty().bind(disabledProperty);
    fetchTimeoutTextField.disableProperty().bind(disabledProperty);
    topicConfigComboBox.disableProperty().bind(disabledProperty);
    offsetResetComboBox.disableProperty().bind(disabledProperty);
    listenerNameTextField.disableProperty().bind(disabledProperty);
}
 
Example #13
Source File: Participant.java    From pikatimer with GNU General Public License v3.0 5 votes vote down vote up
public Participant() {
    fullNameProperty.bind(new StringBinding(){
        {super.bind(firstNameProperty,middleNameProperty, lastNameProperty);}
        @Override
        protected String computeValue() {
            return (firstNameProperty.getValueSafe() + " " + middleNameProperty.getValueSafe() + " " + lastNameProperty.getValueSafe()).replaceAll("( )+", " ");
        }
    });
    
    //Convenience properties for the getDNF and getDQ status checks
    dnfProperty.bind(new BooleanBinding(){
        {super.bind(statusProperty);}
        @Override
        protected boolean computeValue() {
            if (statusProperty.getValue().equals(Status.DNF)) return true;
            return false; 
        }
    });
    dqProperty.bind(new BooleanBinding(){
        {super.bind(statusProperty);}
        @Override
        protected boolean computeValue() {
            if (statusProperty.getValue().equals(Status.DQ)) return true;
            return false; 
        }
    });
    
    waves.addListener(new ListChangeListener<Wave>() {
        @Override
        public void onChanged(Change<? extends Wave> c) {
        
            Platform.runLater(() -> wavesChangedCounterProperty.setValue(wavesChangedCounterProperty.get()+1));
        }
    });
    
    status = Status.GOOD;
    statusProperty.set(status);
    
}
 
Example #14
Source File: SampleController.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
private BooleanBinding makeStringLengthBinding(final StringProperty p){
    return new BooleanBinding() {
        {super.bind(p);}
        
        @Override protected boolean computeValue() {
            int length = p.get().length();
            return length > 0;
        }
    };
}
 
Example #15
Source File: ConnectViewPresenter.java    From mokka7 with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void initialize(URL url, ResourceBundle rb) {

	rack.getItems().addAll(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8));
	rack.getSelectionModel().select(0);
	slot.getItems().addAll(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8));
	slot.getSelectionModel().select(0);

	session.bind(host.textProperty(), "connect.host");

	BooleanBinding disabled = bindings.connectedProperty().or(bindings.progressProperty());
	connect.disableProperty().bind(disabled.or(host.textProperty().isEmpty()));
	host.disableProperty().bind(disabled);
	rack.disableProperty().bind(disabled);
	slot.disableProperty().bind(disabled);
	watchdog.disableProperty().bind(disabled);
	disconnect.disableProperty().bind(bindings.connectedProperty().not().or(bindings.progressProperty()));

	bindings.connectedProperty().addListener((l, a, con) -> update(con));
	pingService.setOnPingFailed(this::pingFailed);

	watchdog.selectedProperty().bindBidirectional(bindings.pingWatchdogProperty());
	session.bind(watchdog.selectedProperty(), "ping.watchdog");
	reset();
}
 
Example #16
Source File: AppUtils.java    From java-ml-projects with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static void disableIfNotSelected(SelectionModel selectionModel, Node... nodes) {
	BooleanBinding selected = selectionModel.selectedItemProperty().isNull();
	for (Node node : nodes) {
		node.disableProperty().bind(selected);
	}
}
 
Example #17
Source File: ErrorBehaviorTest.java    From curly with Apache License 2.0 4 votes vote down vote up
private boolean isBindingTrue(BooleanBinding binding) {
    binding.invalidate();
    sync();
    return binding != null && binding.getValue() != null && binding.get();
}
 
Example #18
Source File: GameModel.java    From Game2048FX with GNU General Public License v3.0 4 votes vote down vote up
public GameModel() {

        Services.get(SettingsService.class)
            .ifPresent(settings -> {
                if (settings.retrieve(GAME_MODE) == null || settings.retrieve(GAME_MODE).isEmpty()) {
                    settings.store(GAME_MODE, Integer.toString(gameMode.get().getMode()));
                }

                if (settings.retrieve(GAME_VIBRATE_MODE_ON) == null || settings.retrieve(GAME_VIBRATE_MODE_ON).isEmpty()) {
                    settings.store(GAME_VIBRATE_MODE_ON, "1");
                }

                if (settings.retrieve(GAME_ID) == null || settings.retrieve(GAME_ID).isEmpty()) {
                    settings.store(GAME_ID, "-1");
                }

                if (settings.retrieve(GAME_LEGACY) == null
                        || settings.retrieve(GAME_LEGACY).isEmpty()
                        || !settings.retrieve(GAME_LEGACY).equals("1")) {

                    GameManager.legacySettings();
                    settings.store(GAME_LEGACY, Integer.toString(1));
                }

                for (GameMode m : GameMode.values()) {
                    if (m.getMode() == Integer.parseInt(settings.retrieve(GAME_MODE))) {
                        gameMode.set(m);
                        break;
                    }
                }
                this.vibrateModeOn.set(settings.retrieve(GAME_VIBRATE_MODE_ON).equals("1"));

                gameManager = new GameManager(4); // default 4x4

                gameModeProperty().addListener((obs, i, i1) -> {
                    gameManager.saveRecord();
                    gameManager.setGameMode(gameMode.get().getMode());
                    gameManager.tryAgain(false);
                });

                switch (getGameMode()) {
                    case EXPERT:
                        saveEnabled.set(false); // Save always disabled
                        restoreEnabled.set(false); // Restore always disabled
                        break;
                    case ADVANCED:
                        // Save only enabled after a new 2048 tile is found
                        saveEnabled.set(gameManager.isTile2048Found());
                        restoreEnabled.set(true); // Restore always enabled
                        break;
                    default:
                        // EASY
                        saveEnabled.set(true); // Save always enabled
                        restoreEnabled.set(true); // Restore always enabled
                        break;
                }

                // Save disabled state, depending on game mode
                BooleanBinding saveBinding = Bindings.createBooleanBinding(() -> {
                    switch (getGameMode()) {
                        case EXPERT:
                            return false;
                        case EASY:
                            return true;
                        default:
                            return gameManager.isTile2048Found();
                    }
                }, gameModeProperty(), gameManager.tile2048FoundProperty());
                saveEnabled.bind(saveBinding);

                // Restore disabled state, depending on game mode
                restoreEnabled.bind(gameModeProperty().isNotEqualTo(GameMode.EXPERT));
            });
    }
 
Example #19
Source File: Login.java    From curly with Apache License 2.0 4 votes vote down vote up
/**
 * @return the requiredFieldsPresent
 */
public BooleanBinding requiredFieldsPresentProperty() {
    return requiredFieldsPresent;
}
 
Example #20
Source File: CheckItemBuilt.java    From AsciidocFX with Apache License 2.0 4 votes vote down vote up
public CheckItemBuilt visible(BooleanBinding binding) {
    menuItem.visibleProperty().bind(binding);
    return this;
}
 
Example #21
Source File: RunnerResult.java    From curly with Apache License 2.0 4 votes vote down vote up
public BooleanBinding completelySuccessful() {
    return completelySuccessfulBinding;
}
 
Example #22
Source File: RunnerResult.java    From curly with Apache License 2.0 4 votes vote down vote up
final public BooleanBinding completed() {
    return completedBinding;
}
 
Example #23
Source File: MainPresenter.java    From clarity-analyzer with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void initialize(java.net.URL location, java.util.ResourceBundle resources) {
    preferences = Preferences.userNodeForPackage(this.getClass());
    replayController = new ReplayController(slider);

    BooleanBinding runnerIsNull = Bindings.createBooleanBinding(() -> replayController.getRunner() == null, replayController.runnerProperty());
    buttonPlay.disableProperty().bind(runnerIsNull.or(replayController.playingProperty()));
    buttonPause.disableProperty().bind(runnerIsNull.or(replayController.playingProperty().not()));
    slider.disableProperty().bind(runnerIsNull);

    labelTick.textProperty().bind(replayController.tickProperty().asString());
    labelLastTick.textProperty().bind(replayController.lastTickProperty().asString());

    TableColumn<ObservableEntity, String> entityTableIdColumn = (TableColumn<ObservableEntity, String>) entityTable.getColumns().get(0);
    entityTableIdColumn.setCellValueFactory(param -> param.getValue() != null ? param.getValue().indexProperty() : new ReadOnlyStringWrapper(""));
    TableColumn<ObservableEntity, String> entityTableNameColumn = (TableColumn<ObservableEntity, String>) entityTable.getColumns().get(1);
    entityTableNameColumn.setCellValueFactory(param -> param.getValue() != null ? param.getValue().nameProperty() : new ReadOnlyStringWrapper(""));
    entityTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        log.info("entity table selection from {} to {}", oldValue, newValue);
        detailTable.setItems(newValue);
    });

    TableColumn<ObservableEntityProperty, String> idColumn =
        (TableColumn<ObservableEntityProperty, String>) detailTable.getColumns().get(0);
    idColumn.setCellValueFactory(param -> param.getValue().indexProperty());
    TableColumn<ObservableEntityProperty, String> nameColumn =
        (TableColumn<ObservableEntityProperty, String>) detailTable.getColumns().get(1);
    nameColumn.setCellValueFactory(param -> param.getValue().nameProperty());
    TableColumn<ObservableEntityProperty, String> valueColumn =
        (TableColumn<ObservableEntityProperty, String>) detailTable.getColumns().get(2);
    valueColumn.setCellValueFactory(param -> param.getValue().valueProperty());

    valueColumn.setCellFactory(v -> new TableCell<ObservableEntityProperty, String>() {
        final Animation animation = new Transition() {
            {
                setCycleDuration(Duration.millis(500));
                setInterpolator(Interpolator.EASE_OUT);
            }
            @Override
            protected void interpolate(double frac) {
                Color col = Color.YELLOW.interpolate(Color.WHITE, frac);
                getTableRow().setStyle(String.format(
                        "-fx-control-inner-background: #%02X%02X%02X;",
                        (int)(col.getRed() * 255),
                        (int)(col.getGreen() * 255),
                        (int)(col.getBlue() * 255)
                ));
            }
        };
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            setText(item);
            ObservableEntityProperty oep = (ObservableEntityProperty) getTableRow().getItem();
            if (oep != null) {
                animation.stop();
                animation.playFrom(Duration.millis(System.currentTimeMillis() - oep.getLastChangedAt()));
            }
        }
    });

    detailTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    detailTable.setOnKeyPressed(e -> {
        KeyCombination ctrlC = new KeyCodeCombination(KeyCode.C, KeyCodeCombination.CONTROL_DOWN);
        if (ctrlC.match(e)) {
            ClipboardContent cbc = new ClipboardContent();
            cbc.putString(detailTable.getSelectionModel().getSelectedIndices().stream()
                    .map(i -> detailTable.getItems().get(i))
                    .map(p -> String.format("%s %s %s", p.indexProperty().get(), p.nameProperty().get(), p.valueProperty().get()))
                    .collect(Collectors.joining("\n"))
            );
            Clipboard.getSystemClipboard().setContent(cbc);
        }
    });


    entityNameFilter.textProperty().addListener(observable -> {
        if (filteredEntityList != null) {
            filteredEntityList.setPredicate(allFilterFunc);
            filteredEntityList.setPredicate(filterFunc);
        }
    });

    mapControl = new MapControl();
    mapCanvasPane.getChildren().add(mapControl);

    mapCanvasPane.setTopAnchor(mapControl, 0.0);
    mapCanvasPane.setBottomAnchor(mapControl, 0.0);
    mapCanvasPane.setLeftAnchor(mapControl, 0.0);
    mapCanvasPane.setRightAnchor(mapControl, 0.0);
    mapCanvasPane.widthProperty().addListener(evt -> resizeMapControl());
    mapCanvasPane.heightProperty().addListener(evt -> resizeMapControl());

}
 
Example #24
Source File: WalletSettingsController.java    From thundernetwork with GNU Affero General Public License v3.0 4 votes vote down vote up
public void initialize(@Nullable KeyParameter aesKey) {
    DeterministicSeed seed = Main.bitcoin.wallet().getKeyChainSeed();
    if (aesKey == null) {
        if (seed.isEncrypted()) {
            log.info("Wallet is encrypted, requesting password first.");
            // Delay execution of this until after we've finished initialising this screen.
            Platform.runLater(() -> askForPasswordAndRetry());
            return;
        }
    } else {
        this.aesKey = aesKey;
        seed = seed.decrypt(checkNotNull(Main.bitcoin.wallet().getKeyCrypter()), "", aesKey);
        // Now we can display the wallet seed as appropriate.
        passwordButton.setText("Remove password");
    }

    // Set the date picker to show the birthday of this wallet.
    Instant creationTime = Instant.ofEpochSecond(seed.getCreationTimeSeconds());
    LocalDate origDate = creationTime.atZone(ZoneId.systemDefault()).toLocalDate();
    datePicker.setValue(origDate);

    // Set the mnemonic seed words.
    final List<String> mnemonicCode = seed.getMnemonicCode();
    checkNotNull(mnemonicCode);    // Already checked for encryption.
    String origWords = Utils.join(mnemonicCode);
    wordsArea.setText(origWords);

    // Validate words as they are being typed.
    MnemonicCode codec = unchecked(MnemonicCode::new);
    TextFieldValidator validator = new TextFieldValidator(wordsArea, text ->
        !didThrow(() -> codec.check(Splitter.on(' ').splitToList(text)))
    );

    // Clear the date picker if the user starts editing the words, if it contained the current wallets date.
    // This forces them to set the birthday field when restoring.
    wordsArea.textProperty().addListener(o -> {
        if (origDate.equals(datePicker.getValue()))
            datePicker.setValue(null);
    });

    BooleanBinding datePickerIsInvalid = or(
            datePicker.valueProperty().isNull(),

            createBooleanBinding(() ->
                    datePicker.getValue().isAfter(LocalDate.now())
            , /* depends on */ datePicker.valueProperty())
    );

    // Don't let the user click restore if the words area contains the current wallet words, or are an invalid set,
    // or if the date field isn't set, or if it's in the future.
    restoreButton.disableProperty().bind(
            or(
                    or(
                            not(validator.valid),
                            equal(origWords, wordsArea.textProperty())
                    ),

                    datePickerIsInvalid
            )
    );

    // Highlight the date picker in red if it's empty or in the future, so the user knows why restore is disabled.
    datePickerIsInvalid.addListener((dp, old, cur) -> {
        if (cur) {
            datePicker.getStyleClass().add("validation_error");
        } else {
            datePicker.getStyleClass().remove("validation_error");
        }
    });
}
 
Example #25
Source File: WalletSettingsController.java    From devcoretalk with GNU General Public License v2.0 4 votes vote down vote up
public void initialize(@Nullable KeyParameter aesKey) {
    DeterministicSeed seed = Main.bitcoin.wallet().getKeyChainSeed();
    if (aesKey == null) {
        if (seed.isEncrypted()) {
            log.info("Wallet is encrypted, requesting password first.");
            // Delay execution of this until after we've finished initialising this screen.
            Platform.runLater(() -> askForPasswordAndRetry());
            return;
        }
    } else {
        this.aesKey = aesKey;
        seed = seed.decrypt(checkNotNull(Main.bitcoin.wallet().getKeyCrypter()), "", aesKey);
        // Now we can display the wallet seed as appropriate.
        passwordButton.setText("Remove password");
    }

    // Set the date picker to show the birthday of this wallet.
    Instant creationTime = Instant.ofEpochSecond(seed.getCreationTimeSeconds());
    LocalDate origDate = creationTime.atZone(ZoneId.systemDefault()).toLocalDate();
    datePicker.setValue(origDate);

    // Set the mnemonic seed words.
    final List<String> mnemonicCode = seed.getMnemonicCode();
    checkNotNull(mnemonicCode);    // Already checked for encryption.
    String origWords = Joiner.on(" ").join(mnemonicCode);
    wordsArea.setText(origWords);

    // Validate words as they are being typed.
    MnemonicCode codec = unchecked(MnemonicCode::new);
    TextFieldValidator validator = new TextFieldValidator(wordsArea, text ->
        !didThrow(() -> codec.check(Splitter.on(' ').splitToList(text)))
    );

    // Clear the date picker if the user starts editing the words, if it contained the current wallets date.
    // This forces them to set the birthday field when restoring.
    wordsArea.textProperty().addListener(o -> {
        if (origDate.equals(datePicker.getValue()))
            datePicker.setValue(null);
    });

    BooleanBinding datePickerIsInvalid = or(
            datePicker.valueProperty().isNull(),

            createBooleanBinding(() ->
                    datePicker.getValue().isAfter(LocalDate.now())
            , /* depends on */ datePicker.valueProperty())
    );

    // Don't let the user click restore if the words area contains the current wallet words, or are an invalid set,
    // or if the date field isn't set, or if it's in the future.
    restoreButton.disableProperty().bind(
            or(
                    or(
                            not(validator.valid),
                            equal(origWords, wordsArea.textProperty())
                    ),

                    datePickerIsInvalid
            )
    );

    // Highlight the date picker in red if it's empty or in the future, so the user knows why restore is disabled.
    datePickerIsInvalid.addListener((dp, old, cur) -> {
        if (cur) {
            datePicker.getStyleClass().add("validation_error");
        } else {
            datePicker.getStyleClass().remove("validation_error");
        }
    });
}
 
Example #26
Source File: CardComponent.java    From FXGLGames with MIT License 4 votes vote down vote up
public BooleanBinding aliveProperty() {
    return alive;
}
 
Example #27
Source File: WalletSettingsController.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public void initialize(@Nullable KeyParameter aesKey) {
    DeterministicSeed seed = Main.bitcoin.wallet().getKeyChainSeed();
    if (aesKey == null) {
        if (seed.isEncrypted()) {
            log.info("Wallet is encrypted, requesting password first.");
            // Delay execution of this until after we've finished initialising this screen.
            Platform.runLater(() -> askForPasswordAndRetry());
            return;
        }
    } else {
        this.aesKey = aesKey;
        seed = seed.decrypt(checkNotNull(Main.bitcoin.wallet().getKeyCrypter()), "", aesKey);
        // Now we can display the wallet seed as appropriate.
        passwordButton.setText("Remove password");
    }

    // Set the date picker to show the birthday of this wallet.
    Instant creationTime = Instant.ofEpochSecond(seed.getCreationTimeSeconds());
    LocalDate origDate = creationTime.atZone(ZoneId.systemDefault()).toLocalDate();
    datePicker.setValue(origDate);

    // Set the mnemonic seed words.
    final List<String> mnemonicCode = seed.getMnemonicCode();
    checkNotNull(mnemonicCode);    // Already checked for encryption.
    String origWords = Utils.join(mnemonicCode);
    wordsArea.setText(origWords);

    // Validate words as they are being typed.
    MnemonicCode codec = unchecked(MnemonicCode::new);
    TextFieldValidator validator = new TextFieldValidator(wordsArea, text ->
        !didThrow(() -> codec.check(Splitter.on(' ').splitToList(text)))
    );

    // Clear the date picker if the user starts editing the words, if it contained the current wallets date.
    // This forces them to set the birthday field when restoring.
    wordsArea.textProperty().addListener(o -> {
        if (origDate.equals(datePicker.getValue()))
            datePicker.setValue(null);
    });

    BooleanBinding datePickerIsInvalid = or(
            datePicker.valueProperty().isNull(),

            createBooleanBinding(() ->
                    datePicker.getValue().isAfter(LocalDate.now())
            , /* depends on */ datePicker.valueProperty())
    );

    // Don't let the user click restore if the words area contains the current wallet words, or are an invalid set,
    // or if the date field isn't set, or if it's in the future.
    restoreButton.disableProperty().bind(
            or(
                    or(
                            not(validator.valid),
                            equal(origWords, wordsArea.textProperty())
                    ),

                    datePickerIsInvalid
            )
    );

    // Highlight the date picker in red if it's empty or in the future, so the user knows why restore is disabled.
    datePickerIsInvalid.addListener((dp, old, cur) -> {
        if (cur) {
            datePicker.getStyleClass().add("validation_error");
        } else {
            datePicker.getStyleClass().remove("validation_error");
        }
    });
}
 
Example #28
Source File: CheckItemBuilt.java    From AsciidocFX with Apache License 2.0 4 votes vote down vote up
public CheckItemBuilt bind(BooleanBinding binding) {
    menuItem.selectedProperty().bind(binding);
    return this;
}
 
Example #29
Source File: LogPane.java    From pdfsam with GNU Affero General Public License v3.0 4 votes vote down vote up
@Inject
public LogPane(LogListView view) {
    this.logView = view;
    getStyleClass().addAll(Style.CONTAINER.css());
    setCenter(this.logView);

    I18nContext i18n = DefaultI18nContext.getInstance();
    MenuItem copyItem = new MenuItem(i18n.i18n("Copy"));
    copyItem.setId("copyLogMenuItem");
    copyItem.setAccelerator(new KeyCodeCombination(KeyCode.C, KeyCombination.SHORTCUT_DOWN));
    copyItem.setOnAction(e -> copyLog(logView.getSelectionModel().getSelectedItems()));

    // disable if no selection
    copyItem.disableProperty().bind(new BooleanBinding() {
        {
            bind(logView.getSelectionModel().getSelectedIndices());
        }

        @Override
        protected boolean computeValue() {
            return logView.getSelectionModel().getSelectedItems().isEmpty();
        }
    });

    MenuItem clearItem = new MenuItem(i18n.i18n("Clear"));
    clearItem.setId("clearLogMenuItem");
    clearItem.setOnAction(e -> logView.getItems().clear());
    // disable if there's no text
    clearItem.disableProperty().bind(new BooleanBinding() {
        {
            bind(logView.getItems());
        }

        @Override
        protected boolean computeValue() {
            return logView.getItems().isEmpty();
        }
    });

    MenuItem selectAllItem = new MenuItem(i18n.i18n("Select all"));
    selectAllItem.setId("selectAllLogMenuItem");
    selectAllItem.setOnAction(e -> logView.getSelectionModel().selectAll());
    // disable if there's no text
    selectAllItem.disableProperty().bind(clearItem.disableProperty());

    MenuItem saveItem = new MenuItem(i18n.i18n("Save log"));
    saveItem.setId("saveLogMenuItem");
    saveItem.setOnAction(e -> saveLog());
    // disable if there's no text
    saveItem.disableProperty().bind(clearItem.disableProperty());
    SeparatorMenuItem separator = new SeparatorMenuItem();
    logView.setContextMenu(new ContextMenu(copyItem, clearItem, selectAllItem, separator, saveItem));
    logView.focusedProperty().addListener(o -> eventStudio().broadcast(new LogAreaVisiblityChangedEvent()));
}
 
Example #30
Source File: WalletSettingsController.java    From thunder with GNU Affero General Public License v3.0 4 votes vote down vote up
public void initialize (@Nullable KeyParameter aesKey) {
    DeterministicSeed seed = Main.wallet.getKeyChainSeed();
    if (aesKey == null) {
        if (seed.isEncrypted()) {
            log.info("Wallet is encrypted, requesting password first.");
            // Delay execution of this until after we've finished initialising this screen.
            Platform.runLater(() -> askForPasswordAndRetry());
            return;
        }
    } else {
        this.aesKey = aesKey;
        seed = seed.decrypt(checkNotNull(Main.wallet.getKeyCrypter()), "", aesKey);
        // Now we can display the wallet seed as appropriate.
        passwordButton.setText("Remove password");
    }

    // Set the date picker to show the birthday of this wallet.
    Instant creationTime = Instant.ofEpochSecond(seed.getCreationTimeSeconds());
    LocalDate origDate = creationTime.atZone(ZoneId.systemDefault()).toLocalDate();
    datePicker.setValue(origDate);

    // Set the mnemonic seed words.
    final List<String> mnemonicCode = seed.getMnemonicCode();
    checkNotNull(mnemonicCode);    // Already checked for encryption.
    String origWords = Utils.join(mnemonicCode);
    wordsArea.setText(origWords);

    // Validate words as they are being typed.
    MnemonicCode codec = unchecked(MnemonicCode::new);
    TextFieldValidator validator = new TextFieldValidator(wordsArea, text ->
            !didThrow(() -> codec.check(Splitter.on(' ').splitToList(text)))
    );

    // Clear the date picker if the user starts editing the words, if it contained the current wallets date.
    // This forces them to set the birthday field when restoring.
    wordsArea.textProperty().addListener(o -> {
        if (origDate.equals(datePicker.getValue())) {
            datePicker.setValue(null);
        }
    });

    BooleanBinding datePickerIsInvalid = or(
            datePicker.valueProperty().isNull(),

            createBooleanBinding(() ->
                            datePicker.getValue().isAfter(LocalDate.now())
                    , /* depends on */ datePicker.valueProperty())
    );

    // Don't let the user click restore if the words area contains the current wallet words, or are an invalid set,
    // or if the date field isn't set, or if it's in the future.
    restoreButton.disableProperty().bind(
            or(
                    or(
                            not(validator.valid),
                            equal(origWords, wordsArea.textProperty())
                    ),

                    datePickerIsInvalid
            )
    );

    // Highlight the date picker in red if it's empty or in the future, so the user knows why restore is disabled.
    datePickerIsInvalid.addListener((dp, old, cur) -> {
        if (cur) {
            datePicker.getStyleClass().add("validation_error");
        } else {
            datePicker.getStyleClass().remove("validation_error");
        }
    });
}