Example usage for javafx.beans InvalidationListener InvalidationListener

List of usage examples for javafx.beans InvalidationListener InvalidationListener

Introduction

In this page you can find the example usage for javafx.beans InvalidationListener InvalidationListener.

Prototype

InvalidationListener

Source Link

Usage

From source file:Main.java

public static void main(String[] args) {
        SimpleIntegerProperty xProperty = new SimpleIntegerProperty(0);

        // Adding a invalidation listener (anonymous inner class)
        xProperty.addListener(new InvalidationListener() {
            @Override//w  w w .java 2s  . c  o  m
            public void invalidated(Observable o) {
                System.out.println(o.toString());
            }
        });

        // Adding a invalidation listener (lambda expression)
        xProperty.addListener((Observable o) -> {
            System.out.println(o.toString());
        });

    }

From source file:MyClass.java

public static void main(String[] args) {

    MyClass myObject1 = new MyClass();
    MyClass myObject2 = new MyClass();
    MyClass myObject3 = new MyClass();

    NumberBinding total = Bindings.add(myObject1.amountDueProperty().add(myObject2.amountDueProperty()),
            myObject3.amountDueProperty());
    total.addListener(new InvalidationListener() {
        @Override/*from ww w.ja  v a 2  s  .co  m*/
        public void invalidated(Observable o) {
            System.out.println("The binding is now invalid.");
        }
    });
    myObject1.setAmountDue(200.00);
    myObject2.setAmountDue(100.00);
    myObject3.setAmountDue(75.00);
    System.out.println(total.getValue());
    myObject3.setAmountDue(150.00);
    System.out.println(total.getValue());
}

From source file:Main.java

@Override
public void start(Stage stage) throws Exception {
    ImageView imageView = new ImageView();
    ScrollPane scrollPane = new ScrollPane();
    DoubleProperty zoomProperty = new SimpleDoubleProperty(200);

    zoomProperty.addListener(new InvalidationListener() {
        @Override/*from   w  w w  . j a v  a2 s .co  m*/
        public void invalidated(Observable arg0) {
            imageView.setFitWidth(zoomProperty.get() * 2);
            imageView.setFitHeight(zoomProperty.get() * 3);
        }
    });
    scrollPane.addEventFilter(ScrollEvent.ANY, new EventHandler<ScrollEvent>() {
        @Override
        public void handle(ScrollEvent event) {
            if (event.getDeltaY() > 0) {
                zoomProperty.set(zoomProperty.get() * 1.2);
            } else if (event.getDeltaY() < 0) {
                zoomProperty.set(zoomProperty.get() / 1.1);
            }
        }
    });
    imageView.setImage(new Image("http://yourImageURL"));
    imageView.preserveRatioProperty().set(true);
    scrollPane.setContent(imageView);
    stage.setScene(new Scene(scrollPane, 400, 300));
    stage.show();
}

From source file:ZoomExample.java

@Override
public void start(Stage stage) throws Exception {

    zoomProperty.addListener(new InvalidationListener() {
        @Override/*from ww  w .j  av  a  2s  .  c o  m*/
        public void invalidated(Observable arg0) {
            imageView.setFitWidth(zoomProperty.get() * 4);
            imageView.setFitHeight(zoomProperty.get() * 3);
        }
    });

    scrollPane.addEventFilter(ScrollEvent.ANY, new EventHandler<ScrollEvent>() {
        @Override
        public void handle(ScrollEvent event) {
            if (event.getDeltaY() > 0) {
                zoomProperty.set(zoomProperty.get() * 1.1);
            } else if (event.getDeltaY() < 0) {
                zoomProperty.set(zoomProperty.get() / 1.1);
            }
        }
    });

    imageView.setImage(new Image("http://yourImageURL"));
    imageView.preserveRatioProperty().set(true);
    scrollPane.setContent(imageView);

    stage.setScene(new Scene(scrollPane, 400, 300));
    stage.show();

}

From source file:ca.wumbo.doommanager.client.controller.file.DoomFileController.java

@FXML
private void initialize() {
    // Keep the left window the same size when resizing/maximizing.
    SplitPane.setResizableWithParent(leftBorderPane, false);

    // Allow selection of multiple cells.
    entryTreeTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    // Make the cells update accordingly.
    nameColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().entryProperty());
    sizeColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().dataLengthStringProperty());
    typeColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().entryTypeProperty());

    // Resize the splitter to a reasonable position.
    // Since we can't use Platform.runlater() to do this, we have to use a listener that removes itself.
    // Note: The old way it was done was to pass the tabPane's width to the function after this is initialized.
    InvalidationListener invalidationListener = new InvalidationListener() {
        @Override// ww w.ja  v  a  2 s.  c o m
        public void invalidated(Observable observable) {
            setSplitterPosition((int) splitPane.getWidth());
            splitPane.widthProperty().removeListener(this); // Remove itself after the size is set.
        }
    };
    splitPane.widthProperty().addListener(invalidationListener);

    // Handle item selection. This will clean up our GUI and add/remove panes on the right of the splitter.
    entryTreeTable.getSelectionModel().selectedItemProperty().addListener((obsValue, oldValue, newValue) -> {
        updateGUIFromEntrySelection(oldValue, newValue);
    });

    // Support right clicking menus on the rows, source: https://gist.github.com/james-d/7758918
    entryTreeTable.setRowFactory(new Callback<TreeTableView<Entry>, TreeTableRow<Entry>>() {
        @Override
        public TreeTableRow<Entry> call(TreeTableView<Entry> tableView) {
            // Create the row to return.
            TreeTableRow<Entry> row = new TreeTableRow<>();
            ContextMenu contextMenu = new ContextMenu();

            // Whenever this row gets a new item (or is updated), rebuild the right click menu.
            row.itemProperty().addListener((observableValue, oldValue, newValue) -> {
                // TODO - Dynamically generate a new context menu - contextMenu.getItems().add(new MenuItem());
            });

            // Set context menu on row, but use a binding to make it only show for non-empty rows:
            row.contextMenuProperty()
                    .bind(Bindings.when(row.emptyProperty()).then((ContextMenu) null).otherwise(contextMenu));

            return row;
        }
    });

    // Instead of assigning graphics to each node, only do it for the cells.
    // This should help reduce object creation by having it only required for the visible rows.
    nameColumn.setCellFactory(new Callback<TreeTableColumn<Entry, Entry>, TreeTableCell<Entry, Entry>>() {
        @Override
        public TreeTableCell<Entry, Entry> call(TreeTableColumn<Entry, Entry> param) {
            return new TreeTableCell<Entry, Entry>() {
                @Override
                protected void updateItem(Entry item, boolean empty) {
                    super.updateItem(item, empty);
                    if (!empty && item != null) {
                        setText(item.getName());
                        Image img = resources.getImage(item.getClass().getSimpleName().toLowerCase());
                        setGraphic(new ImageView(img));
                    } else {
                        setText(null);
                        setGraphic(null);
                    }
                }
            };
        }
    });
}

From source file:MediaControl.java

public MediaControl(final MediaPlayer mp) {
    this.mp = mp;
    setStyle("-fx-background-color: #bfc2c7;");
    mediaView = new MediaView(mp);
    Pane mvPane = new Pane() {
    };/*from ww  w . j a  v  a2  s .c  o  m*/
    mvPane.getChildren().add(mediaView);
    mvPane.setStyle("-fx-background-color: black;");
    setCenter(mvPane);
    mediaBar = new HBox();
    mediaBar.setAlignment(Pos.CENTER);
    mediaBar.setPadding(new Insets(5, 10, 5, 10));
    BorderPane.setAlignment(mediaBar, Pos.CENTER);

    final Button playButton = new Button(">");

    playButton.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            Status status = mp.getStatus();

            if (status == Status.UNKNOWN || status == Status.HALTED) {
                // don't do anything in these states
                return;
            }

            if (status == Status.PAUSED || status == Status.READY || status == Status.STOPPED) {
                // rewind the movie if we're sitting at the end
                if (atEndOfMedia) {
                    mp.seek(mp.getStartTime());
                    atEndOfMedia = false;
                }
                mp.play();
            } else {
                mp.pause();
            }
        }
    });
    mp.currentTimeProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            updateValues();
        }
    });

    mp.setOnPlaying(new Runnable() {
        public void run() {
            if (stopRequested) {
                mp.pause();
                stopRequested = false;
            } else {
                playButton.setText("||");
            }
        }
    });

    mp.setOnPaused(new Runnable() {
        public void run() {
            System.out.println("onPaused");
            playButton.setText(">");
        }
    });

    mp.setOnReady(new Runnable() {
        public void run() {
            duration = mp.getMedia().getDuration();
            updateValues();
        }
    });

    mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
    mp.setOnEndOfMedia(new Runnable() {
        public void run() {
            if (!repeat) {
                playButton.setText(">");
                stopRequested = true;
                atEndOfMedia = true;
            }
        }
    });
    mediaBar.getChildren().add(playButton);
    // Add spacer
    Label spacer = new Label("   ");
    mediaBar.getChildren().add(spacer);

    // Add Time label
    Label timeLabel = new Label("Time: ");
    mediaBar.getChildren().add(timeLabel);

    // Add time slider
    timeSlider = new Slider();
    HBox.setHgrow(timeSlider, Priority.ALWAYS);
    timeSlider.setMinWidth(50);
    timeSlider.setMaxWidth(Double.MAX_VALUE);

    timeSlider.valueProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            if (timeSlider.isValueChanging()) {
                // multiply duration by percentage calculated by slider position
                mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
            }
        }
    });

    mediaBar.getChildren().add(timeSlider);

    // Add Play label
    playTime = new Label();
    playTime.setPrefWidth(130);
    playTime.setMinWidth(50);
    mediaBar.getChildren().add(playTime);

    // Add the volume label
    Label volumeLabel = new Label("Vol: ");
    mediaBar.getChildren().add(volumeLabel);

    // Add Volume slider
    volumeSlider = new Slider();
    volumeSlider.setPrefWidth(70);
    volumeSlider.setMaxWidth(Region.USE_PREF_SIZE);
    volumeSlider.setMinWidth(30);
    volumeSlider.valueProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            if (volumeSlider.isValueChanging()) {
                mp.setVolume(volumeSlider.getValue() / 100.0);
            }
        }
    });
    mediaBar.getChildren().add(volumeSlider);
    setBottom(mediaBar);
}

From source file:com.panemu.tiwulfx.table.BaseColumn.java

/**
 *
 * @param propertyName java bean property name to be used for get/set method
 * using introspection/*from  w w w. jav a 2 s. com*/
 * @param prefWidth preferred collumn width
 * @param columnHeader column header text. Default equals propertyName. This
 * text is localized
 */
public BaseColumn(String propertyName, double prefWidth, String columnHeader) {
    super(columnHeader);
    setPrefWidth(prefWidth);
    this.propertyName = propertyName;
    //        setCellValueFactory(new PropertyValueFactory<S, T>(propertyName));
    tableCriteria.addListener(new InvalidationListener() {
        @Override
        public void invalidated(Observable observable) {
            if (tableCriteria.get() != null) {
                BaseColumn.this.setGraphic(filterImage);
            } else {
                BaseColumn.this.setGraphic(null);
            }
        }
    });
    setCellValueFactory(new Callback<CellDataFeatures<R, C>, ObservableValue<C>>() {
        private SimpleObjectProperty<C> propertyValue;

        @Override
        public ObservableValue<C> call(CellDataFeatures<R, C> param) {
            /**
             * This code is adapted from {@link PropertyValueFactory#getCellDataReflectively(T)
             */
            try {
                Object cellValue;
                if (getPropertyName().contains(".")) {
                    cellValue = PropertyUtils.getNestedProperty(param.getValue(), getPropertyName());
                } else {
                    cellValue = PropertyUtils.getSimpleProperty(param.getValue(), getPropertyName());
                }
                propertyValue = new SimpleObjectProperty<>((C) cellValue);
                return propertyValue;
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                throw new RuntimeException(ex);
            } catch (Exception ex) {
                /**
                 * Ideally it catches
                 * org.apache.commons.beanutils.NestedNullException. However
                 * we need to import apachec bean utils library in FXML file
                 * to be able to display it in Scene Builder. So, I decided
                 * to catch Exception to avoid the import.
                 */
                return new SimpleObjectProperty<>(null);
            }
        }
    });

}

From source file:com.panemu.tiwulfx.control.skin.LookupFieldSkin.java

private void initialize() {
    textField = new TextField();
    textField.setFocusTraversable(true);
    textField.setEditable(!lookupField.getDisableManualInput());
    textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
        @Override/*ww w  .  j av a  2  s . co m*/
        public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean hasFocus) {
            textField.selectEnd();
        }
    });

    button = new Button();
    button.setFocusTraversable(false);
    button.setGraphic(TiwulFXUtil.getGraphicFactory().createLookupGraphic());
    StackPane.setAlignment(textField, Pos.CENTER_LEFT);
    StackPane.setAlignment(button, Pos.CENTER_RIGHT);
    this.getChildren().addAll(textField, button);
    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent t) {
            if (!lookupField.isFocused()) {
                /**
                 * Need to make this control become focused. Otherwise
                 * changing value in LookupColumn while the LookuField cell
                 * editor
                 * is not focused before, won't trigger commitEdit()
                 */
                lookupField.requestFocus();
            }
            getSkinnable().showLookupDialog();
        }
    });
    updateTextField();
    lookupField.valueProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue ov, Object t, Object t1) {
            updateTextField();
        }
    });

    lookupField.markInvalidProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (oldValue && !newValue && needValidation) {
                validate();
            }
        }
    });

    textField.textProperty().addListener(new InvalidationListener() {
        @Override
        public void invalidated(Observable o) {
            if (detectTextChanged) {
                if (waitTimer != null) {
                    loaderTimerTask.setObsolete(true);
                    waitTimer.cancel();
                    waitTimer.purge();
                }

                if (textField.getText() == null || textField.getText().trim().isEmpty()) {
                    lookupField.setValue(null);
                    return;
                }
                lookupField.markInvalidProperty().set(true);
                needValidation = true;

                if (lookupField.getShowSuggestionWaitTime() >= 0) {
                    waitTimer = new Timer("lookupTimer");
                    loaderTimerTask = new LoaderTimerTask(waitTimer);
                    waitTimer.schedule(loaderTimerTask, lookupField.getShowSuggestionWaitTime());
                }
            }
        }
    });

}

From source file:acmi.l2.clientmod.xdat.Controller.java

private PropertySheet createPropertySheet(TreeView<Object> elements) {
    PropertySheet properties = new PropertySheet();
    properties.setSkin(new PropertySheetSkin(properties));

    elements.getSelectionModel().selectedItemProperty().addListener((selected, oldValue, newSelection) -> {
        properties.getItems().clear();//from w  w w. j  av a  2s.  c om

        if (newSelection == null)
            return;

        Object obj = newSelection.getValue();

        if (obj instanceof ListHolder)
            return;

        if (!map.containsKey(obj.getClass())) {
            map.put(obj.getClass(), loadProperties(obj));
        }
        List<PropertySheetItem> props = map.get(obj.getClass());
        props.forEach(property -> {
            property.setObject(obj);
            ChangeListener<Object> addToHistory = (observable1, oldValue1, newValue) -> editor.getHistory()
                    .valueChanged(treeItemToScriptString(newSelection), property.getName(), newValue);
            property.addListener(addToHistory);

            selected.addListener(new InvalidationListener() {
                @Override
                public void invalidated(Observable observable) {
                    property.removeListener(addToHistory);
                    observable.removeListener(this);
                }
            });
        });
        properties.getItems().setAll(props);
    });

    return properties;
}

From source file:fr.amap.lidar.amapvox.gui.MainFrameController.java

private void showImage(File file) {

    try {/*from  www.  j  ava2 s .  c o  m*/
        ImageView iv = new ImageView(new Image(file.toURI().toURL().toString()));
        iv.setPreserveRatio(true);
        Stage stage = new Stage();

        final DoubleProperty zoomProperty = new SimpleDoubleProperty(200);

        zoomProperty.addListener(new InvalidationListener() {
            @Override
            public void invalidated(javafx.beans.Observable observable) {
                iv.setFitWidth(zoomProperty.get() * 4);
                iv.setFitHeight(zoomProperty.get() * 3);
            }
        });

        ScrollPane sp = new ScrollPane(iv);
        stage.addEventFilter(ScrollEvent.ANY, new EventHandler<ScrollEvent>() {
            @Override
            public void handle(ScrollEvent event) {
                if (event.getDeltaY() > 0) {
                    zoomProperty.set(zoomProperty.get() * 1.1);
                } else if (event.getDeltaY() < 0) {
                    zoomProperty.set(zoomProperty.get() / 1.1);
                }
            }
        });

        stage.setScene(new Scene(new Group(sp)));

        stage.sizeToScene();
        stage.show();
    } catch (IOException ex) {
        showErrorDialog(ex);
    }

}