javafx.beans.value.ObservableValue Java Examples

The following examples show how to use javafx.beans.value.ObservableValue. 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: RFXCheckBoxTreeCell.java    From marathonv5 with Apache License 2.0 7 votes vote down vote up
@Override
public String _getValue() {
    @SuppressWarnings("rawtypes")
    CheckBoxTreeCell cell = (CheckBoxTreeCell) node;
    @SuppressWarnings("unchecked")
    ObservableValue<Boolean> call = (ObservableValue<Boolean>) cell.getSelectedStateCallback().call(cell.getTreeItem());
    String cbText;
    if (call != null) {
        int selection = call.getValue() ? 2 : 0;
        cbText = JavaFXCheckBoxElement.states[selection];
    } else {
        Node cb = cell.getGraphic();
        RFXComponent comp = getFinder().findRawRComponent(cb, null, null);
        cbText = comp._getValue();
    }
    return cbText;
}
 
Example #2
Source File: ClientSession.java    From Open-Lowcode with Eclipse Public License 2.0 7 votes vote down vote up
/**
 * creates the tab pane if required, and adds a tab with the client display
 * 
 * @param clientdisplay the display to show
 */
private void setupDisplay(ClientDisplay clientdisplay) {
	// initiates the tabpane if called for the first time
	if (this.tabpane == null) {
		this.tabpane = new TabPane();
		this.tabpane.setBackground(new Background(new BackgroundFill(Color.WHITE, null, null)));
		this.tabpane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
		this.tabpane.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
			@Override
			public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) {
				int index = newValue.intValue();
				activedisplayindex = index;
				logger.warning(" --> Set active display index afterselection to " + index);
			}
		});
	}
	displayTab(clientdisplay);

}
 
Example #3
Source File: MainStage.java    From oim-fx with MIT License 6 votes vote down vote up
public void addTab(Image normalImage, Image hoverImage, Image selectedImage, Node node) {
	IconToggleButton tb = new IconToggleButton(normalImage, hoverImage, selectedImage);
	tb.setUserData(node);
	tb.setToggleGroup(group);
	tb.selectedProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
		if (oldValue != newValue && newValue) {
			setSelectedNode(node);
			redTab(tb, !newValue);
		}
	});
	tabBox.getChildren().add(tb);
	if (tempTb == null) {
		group.selectToggle(tb);
		tempTb = tb;
	}
	group.selectedToggleProperty().removeListener(listener);
	group.selectedToggleProperty().addListener(listener);
	// group.selectedToggleProperty().addListener((ObservableValue<? extends
	// Toggle> observable, Toggle oldValue, Toggle newValue) -> {
	//
	// if (newValue == null) {
	// group.selectToggle(oldValue);
	// }
	// System.out.println("addTab");
	// });
}
 
Example #4
Source File: BrowserPanel.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private void listenToStateChangesForAdjustingPanelHeightToWebsite() {
    engine.getLoadWorker()
            .stateProperty()
            .addListener(
                    new ChangeListener<Object>() {
                        @Override
                        public void changed(
                                ObservableValue<?> observable,
                                Object oldValue,
                                Object newValue) {
                            if (State.SUCCEEDED == newValue && resizeOnLoad) {
                                resizeOnLoad = false;
                                final int height = getWebsiteHeight();
                                SwingUtilities.invokeLater(
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                setWebsiteHeight(height);
                                            }
                                        });
                            }
                        }
                    });
}
 
Example #5
Source File: CachedTimelineTransition.java    From oim-fx with MIT License 6 votes vote down vote up
/**
 * Create new CachedTimelineTransition
 * 
 * @param node
 *            The node that is being animated by the timeline
 * @param timeline
 *            The timeline for the animation, it should be from 0 to 1
 *            seconds
 * @param useCache
 *            When true the node is cached as image during the animation
 */
public CachedTimelineTransition(final Node node, final Timeline timeline, final boolean useCache) {
	this.node = node;
	this.timeline = timeline;
	this.useCache = useCache;
	statusProperty().addListener(new ChangeListener<Status>() {
		@Override
		public void changed(ObservableValue<? extends Status> ov, Status t, Status newStatus) {
			switch (newStatus) {
			case RUNNING:
				starting();
				break;
			default:
				stopping();
				break;
			}
		}
	});
}
 
Example #6
Source File: LabAssistantController.java    From HealthPlus with Apache License 2.0 6 votes vote down vote up
public void addFocusListener()
{        
    labPassword.focusedProperty().addListener(new ChangeListener<Boolean>()
    {
        @Override
        public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
        {
            if (newPropertyValue)
            {
                System.out.println("Textfield on focus");
            }
            else
            {
                System.out.println("Textfield out focus");
            }
        }
    });
}
 
Example #7
Source File: GeographyCodeSelectorController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
@Override
public void initializeNext() {
    try {
        super.initializeNext();

        FxmlControl.setTooltip(leafCheck, message("CheckLeafNodesComments"));
        leafCheck.setSelected(AppVariables.getUserConfigBoolean("GeographyCodesTreeCheckLeafNodes", true));
        leafCheck.selectedProperty().addListener(
                (ObservableValue<? extends Boolean> ov, Boolean oldValue, Boolean newValue) -> {
                    AppVariables.setUserConfigValue("GeographyCodesTreeCheckLeafNodes", newValue);
                });

    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example #8
Source File: TemplateField.java    From pattypan with MIT License 6 votes vote down vote up
public TemplateField(String name, String label, boolean isSelected, String constant) {
  this.name = name;
  this.label = label;
  this.isSelected = isSelected;
  this.selection = "YES";
  this.value = constant;

  labelElement = new WikiLabel(label).setWidth(200, 500).setHeight(35);
  buttonYes.setSelected(true);

  group.selectedToggleProperty().addListener((ObservableValue<? extends Toggle> ov, Toggle tOld, Toggle tNew) -> {
    RadioButton btn = (RadioButton) tNew.getToggleGroup().getSelectedToggle();
    setSelection(btn.getId());
  });

  valueText.setOnKeyReleased((KeyEvent event) -> {
    this.value = valueText.getText();
  });
}
 
Example #9
Source File: ChatListStage.java    From oim-fx with MIT License 6 votes vote down vote up
private void addItem(String key, ChatItem chatItem) {
	if (!itemVBox.getChildren().contains(chatItem)) {
		itemVBox.getChildren().add(chatItem);
		chatItem.setChooseGroup(chooseGroup);

		ChangeListener<Boolean> cl = changeListenerMap.get(key);
		if (null == cl) {
			cl = new ChangeListener<Boolean>() {

				@Override
				public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
					Node node = chatPaneMap.get(key);
					setChatPane(node);
				}
			};
			changeListenerMap.put(key, cl);
		}
		chatItem.selectedProperty().removeListener(cl);
		chatItem.selectedProperty().addListener(cl);
		chatItem.setOnCloseAction(a -> {
			remove(key);
		});
		itemMap.put(key, chatItem);
	}
}
 
Example #10
Source File: TextEditerController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
@Override
protected void initLineBreakTab() {
    try {
        super.initLineBreakTab();
        lineBreakGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
            @Override
            public void changed(ObservableValue<? extends Toggle> ov,
                    Toggle old_toggle, Toggle new_toggle) {
                checkLineBreakGroup();
            }
        });

    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example #11
Source File: EasyBind.java    From EasyBind with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static <A, B, C, D, E, R> MonadicBinding<R> combine(
        ObservableValue<A> src1,
        ObservableValue<B> src2,
        ObservableValue<C> src3,
        ObservableValue<D> src4,
        ObservableValue<E> src5,
        PentaFunction<A, B, C, D, E, R> f) {
    return new PreboundBinding<R>(src1, src2, src3, src4, src5) {
        @Override
        protected R computeValue() {
            return f.apply(
                    src1.getValue(), src2.getValue(), src3.getValue(),
                    src4.getValue(), src5.getValue());
        }
    };
}
 
Example #12
Source File: PreviewVariablesHandler.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void changed(ObservableValue<? extends Document> observableValue, Document oldDoc, Document newDoc)
{
    if (newDoc == null)
    {
        return;
    }
    NodeList elements = newDoc.getElementsByTagName("input");
    for (int i = 0; i < elements.getLength(); i++)
    {
        HTMLInputElementImpl element = (HTMLInputElementImpl) elements.item(i);
        String key = getInputKey(element);
        if (key == null || key.isEmpty())
        {
            continue;
        }
        setInputValue(element, character.getPreviewSheetVar(key));
        element.addEventListener("change", evt ->
        {
            HTMLInputElement input = (HTMLInputElement) evt.getCurrentTarget();
            character.addPreviewSheetVar(getInputKey(input), getInputValue(input));
        }, false);
    }
}
 
Example #13
Source File: ChatWritePane.java    From oim-fx with MIT License 6 votes vote down vote up
private void iniEvent() {
	webView.setOnInputMethodTextChanged(new EventHandler<InputMethodEvent>() {

		@Override
		public void handle(InputMethodEvent e) {
			processInputMethodEvent(e);
		}
	});
	webView.setOnDragDropped(a -> {

	});

	webEngine.getLoadWorker().stateProperty().addListener((ObservableValue<? extends State> ov, State oldState, State newState) -> {

		if (newState == State.SUCCEEDED) {
			initWeb(webEngine);
		}
	});

	webView.addEventHandler(KeyEvent.ANY,
			event -> {
			});

}
 
Example #14
Source File: ViewArrow.java    From latexdraw with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void createArc(final double cx, final double cy, final double rx, final double ry, final double angle, final double length,
					final ObservableValue<Color> strokeProp, final ObservableDoubleValue strokeWidthProp) {
	arc.setCenterX(cx);
	arc.setCenterY(cy);
	arc.setRadiusX(rx);
	arc.setRadiusY(ry);
	arc.setStartAngle(angle);
	arc.setLength(length);
	arc.strokeProperty().unbind();
	arc.strokeProperty().bind(strokeProp);
	arc.strokeWidthProperty().unbind();
	arc.strokeWidthProperty().bind(strokeWidthProp);
	arc.setFill(null);
	enableShape(false, true, false);
}
 
Example #15
Source File: CN1CSSCLI.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private static void startImpl(Stage stage) throws Exception {
    System.out.println("Opening JavaFX Webview to render some CSS styles");
    web = new WebView();
    web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {
        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            System.out.println("Received exception: "+t1.getMessage());
        }
    });
    
    Scene scene = new Scene(web, 400, 800, Color.web("#666670"));
    stage.setScene(scene);
    stage.show();
    synchronized(lock) {
        lock.notify();
    }
}
 
Example #16
Source File: ProductFetcherTask.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public ProductFetcherTask(final TableView products) {
    valueProperty().addListener(new ChangeListener<ObservableList<FullProductListing>>() {
        @Override public void changed(ObservableValue<? extends ObservableList<FullProductListing>> ov, 
                ObservableList<FullProductListing> oldValues, ObservableList<FullProductListing> newValues) {
            // insert results into table
            products.setItems(newValues);
            // remove progress indicator
            products.setPlaceholder(null);
        }
    });
}
 
Example #17
Source File: PopOver.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a pop over with a label as the content node.
 */
public PopOver() {
    super();

    getStyleClass().add(DEFAULT_STYLE_CLASS);

    setAnchorLocation(AnchorLocation.WINDOW_TOP_LEFT);
    setOnHiding(new EventHandler<WindowEvent>() {
        @Override
        public void handle(WindowEvent evt) {
            setDetached(false);
        }
    });

    /*
     * Create some initial content.
     */
    Label label = new Label("<No Content>"); //$NON-NLS-1$
    label.setPrefSize(200, 200);
    label.setPadding(new Insets(4));
    setContentNode(label);

    ChangeListener<Object> repositionListener = new ChangeListener<Object>() {
        @Override
        public void changed(ObservableValue<? extends Object> value,
                            Object oldObject, Object newObject) {
            if (isShowing() && !isDetached()) {
                show(getOwnerNode(), targetX, targetY);
                adjustWindowLocation();
            }
        }
    };

    arrowSize.addListener(repositionListener);
    cornerRadius.addListener(repositionListener);
    arrowLocation.addListener(repositionListener);
    arrowIndent.addListener(repositionListener);
}
 
Example #18
Source File: StreamDebuggerController.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
public void init(CameraManager cameraManager) {
	streamDebuggerStage = (Stage) thresholdImageView.getScene().getWindow();
	defaultWindowTitle = streamDebuggerStage.getTitle();

	cameraManager.setThresholdListener(this);

	minDimSlider.valueProperty().addListener(new ChangeListener<Number>() {
		@Override
		public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) {
			if (newValue == null) return;

			cameraManager.setMinimumShotDimension(newValue.intValue());
		}
	});
}
 
Example #19
Source File: OptionsDisplaySetupPanel.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new display setup panel.
 *
 * @param bindings HashMap of bindings to setup after the dialog has been created
 */
OptionsDisplaySetupPanel(HashMap<Field, ObservableValue> bindings) {
    this.bindings = bindings;
    controlScreen = new DisplayGroup(LabelGrabber.INSTANCE.getLabel("control.screen.label"), false, bindings);
    projectorScreen = new DisplayGroup(LabelGrabber.INSTANCE.getLabel("projector.screen.label"), true, bindings);
    stageScreen = new DisplayGroup(LabelGrabber.INSTANCE.getLabel("stage.screen.label"), true, bindings);

    GraphicsDeviceWatcher.INSTANCE.addGraphicsDeviceListener(devices -> {
        QueleaApp.get().getMainWindow().getPreferencesDialog().updatePos();
    });
}
 
Example #20
Source File: ClientLoginNode.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
private void initialize() {

        nextbutton.setGraphic(IconBuilder.create(IconFontGlyph.FA_SOLID_PLAY, 18.0).styleClass("icon-fill").build());

        adddeviceunit.setGraphic(IconBuilder.create(IconFontGlyph.FA_SOLID_FILE_ALT, 18.0).styleClass("icon-fill").build());
        adddeviceunit.setText(resources.getString("title.new"));
        
        removedeviceunit.setGraphic(IconBuilder.create(IconFontGlyph.FA_SOLID_TRASH_ALT, 18.0).styleClass("icon-fill").build());
        updeviceunit.setGraphic(IconBuilder.create(IconFontGlyph.FA_SOLID_CHEVRON_UP, 18.0).styleClass("icon-fill").build());
        downdeviceunit.setGraphic(IconBuilder.create(IconFontGlyph.FA_SOLID_CHEVRON_DOWN, 18.0).styleClass("icon-fill").build());

        devicesunitsselection.selectedItemProperty().addListener((ObservableValue<? extends TopicInfo> ov, TopicInfo old_val, TopicInfo new_val) -> {
            updateDevicesUnitsList();
        });
        updateDevicesUnitsList();
        
        skins.setConverter(new StringConverter<Style>() {
            @Override
            public String toString(Style style) {
                return resources.getString("style." + style.name());
            }
            @Override
            public Style fromString(String value) {
                return null;
            }
        });
        skins.getItems().addAll(Style.values());
        skins.getSelectionModel().selectedItemProperty().addListener((ov, old_val, new_val) -> {
            if (!updating) {
                Style.changeStyle(MessageUtils.getRoot(rootpane), new_val);
            }
        });
    }
 
Example #21
Source File: TopicConfigComboBoxConfigurator.java    From kafka-message-tool with MIT License 5 votes vote down vote up
private void comboBoxSelectionChangedCallback(ObservableValue<? extends RelatedConfig> ignored1,
                                              RelatedConfig oldValue,
                                              RelatedConfig newValue) {
    if (comboBoxUpdateMode == ComboBoxUpdateMode.Normal) {
        config.setRelatedConfig(newValue);
    }
}
 
Example #22
Source File: Controller.java    From xdat_editor with MIT License 5 votes vote down vote up
private TreeView<Object> createTreeView(Field listField, ObservableValue<String> filter) {
    TreeView<Object> elements = new TreeView<>();
    elements.setCellFactory(param -> new TreeCell<Object>() {
        @Override
        protected void updateItem(Object item, boolean empty) {
            super.updateItem(item, empty);

            if (item == null || empty) {
                setText(null);
                setGraphic(null);
            } else {
                setText(item.toString());
                if (UIEntity.class.isAssignableFrom(item.getClass())) {
                    try (InputStream is = getClass().getResourceAsStream("/acmi/l2/clientmod/xdat/nodeicons/" + UI_NODE_ICONS.getOrDefault(item.getClass().getSimpleName(), UI_NODE_ICON_DEFAULT))) {
                        setGraphic(new ImageView(new Image(is)));
                    } catch (IOException ignore) {}
                }
            }
        }
    });
    elements.setShowRoot(false);
    elements.setContextMenu(createContextMenu(elements));

    InvalidationListener treeInvalidation = (observable) -> buildTree(editor.xdatObjectProperty().get(), listField, elements, filter.getValue());
    editor.xdatObjectProperty().addListener(treeInvalidation);
    xdatListeners.add(treeInvalidation);

    filter.addListener(treeInvalidation);

    return elements;
}
 
Example #23
Source File: MainFlatPane.java    From oim-fx with MIT License 5 votes vote down vote up
void initEvent() {
	group.selectedToggleProperty().addListener((ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) -> {
		if (newValue == null) {
			group.selectToggle(oldValue);
		}
	});
}
 
Example #24
Source File: OptionsController.java    From CPUSim with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initializes the indexing tab
 */
private void initializeIndexingTab() {

    changeIndexingDirection = false;

    ChangeListener indexChangeListener = new ChangeListener() {
        @Override
        public void changed(ObservableValue ov, Object t, Object t1) {
            changeIndexingDirection = !changeIndexingDirection;
        }
    };

    indexChoice.setValue(mediator.getMachine().getIndexFromRight() ? "right" : "left");
    indexChoice.getSelectionModel().selectedIndexProperty().addListener(indexChangeListener);
}
 
Example #25
Source File: AuditLogTaskRecord.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public AuditLogTaskRecord(@Nonnull Task<?> task) {
  this.taskMessage = task.getMessage();
  this.taskTitle = task.getTitle();

  task.stateProperty().addListener(new ChangeListener<State>() {
    public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
      taskStatus = newState;
    }
  });

}
 
Example #26
Source File: YfitonWebEngineListener.java    From yfiton with Apache License 2.0 5 votes vote down vote up
@Override
public void doAction(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) {
    String location = webEngine.getLocation();

    if (newValue == Worker.State.SUCCEEDED
            && location.startsWith(OAuthNotifier.YFITON_OAUTH_CALLBACK_URL)) {

        AuthorizationData transformed = getParameters(location);

        save(transformed);
    }
}
 
Example #27
Source File: PaintingComponentContainer.java    From jmonkeybuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Activate the selected painting component.
 *
 * @param observable the component box's property.
 * @param oldValue   the previous component.
 * @param newValue   the new component.
 */
@FxThread
private void activate(
        @NotNull ObservableValue<? extends PaintingComponent> observable,
        @Nullable PaintingComponent oldValue,
        @Nullable PaintingComponent newValue
) {

    var items = getContainer().getChildren();

    if (oldValue != null) {
        oldValue.notifyHided();
        oldValue.stopPainting();
        items.remove(oldValue);
    }

    var paintedObject = getPaintedObject();

    if (newValue != null) {

        if (paintedObject != null) {
            newValue.startPainting(paintedObject);
        }

        if (isShowed()) {
            newValue.notifyShowed();
        }

        items.add((Node) newValue);
    }

    setCurrentComponent(newValue);
}
 
Example #28
Source File: PdfOcrBatchController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
protected void initOCROptionsBox() {
    try {
        languageList.getItems().clear();
        languageList.getItems().addAll(OCRTools.namesList());
        languageList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        languageList.setPrefHeight(200);
        languageList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> ov, String oldVal, String newVal) {
                checkLanguages();
            }
        });
        selectedLanguages = AppVariables.getUserConfigValue("ImageOCRLanguages", null);
        if (selectedLanguages != null && !selectedLanguages.isEmpty()) {
            currentOCRFilesLabel.setText(
                    MessageFormat.format(message("CurrentDataFiles"), selectedLanguages));
            isSettingValues = true;
            String[] langs = selectedLanguages.split("\\+");
            Map<String, String> codes = OCRTools.codeName();
            for (String code : langs) {
                String name = codes.get(code);
                if (name == null) {
                    name = code;
                }
                languageList.getSelectionModel().select(name);
            }
            isSettingValues = false;
        } else {
            currentOCRFilesLabel.setText(
                    MessageFormat.format(message("CurrentDataFiles"), ""));
        }

        FxmlControl.setTooltip(separatorInput, message("InsertPageSeparatorComments"));

    } catch (Exception e) {
        logger.debug(e.toString());
    }
}
 
Example #29
Source File: BaseGraphApp.java    From diirt with MIT License 5 votes vote down vote up
public DataSelectionPanel() {
    this.setPadding( new Insets( 5 , 5 , 5 , 5 ) );

    GridPane pnlCenter = new GridPane();
    pnlCenter.setHgap( 5 );
    this.cboSelectData.setPrefWidth( 0 );
    pnlCenter.addRow( 0 , this.lblData , this.cboSelectData , this.cmdConfigure );

    ColumnConstraints allowResize = new ColumnConstraints();
    allowResize.setHgrow( Priority.ALWAYS );
    ColumnConstraints noResize = new ColumnConstraints();
    pnlCenter.getColumnConstraints().addAll( noResize , allowResize , noResize );

    this.setCenter( pnlCenter );

    //allow the combo box to stretch out and fill panel completely
    this.cboSelectData.setMaxSize( Double.MAX_VALUE , Double.MAX_VALUE );
    this.cboSelectData.setEditable( true );

    //watches for when the user selects a new data formula
    cboSelectData.valueProperty().addListener( new ChangeListener< String >() {

        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            pnlGraph.setFormula(newValue);
        }

    });

    this.cmdConfigure.setOnAction( new EventHandler< ActionEvent >() {

        @Override
        public void handle(ActionEvent event) {
            openConfigurationPanel();
        }

    });
}
 
Example #30
Source File: VideoMp4.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
private MediaPlayer getMediaPlayerFor(Media media) {
    try {
        playerReady = false;
        final MediaPlayer mediaPlayer = new MediaPlayer(media);
        if(mediaPlayer.getError() == null) {
            mediaPlayer.setAutoPlay(false);
            mediaPlayer.currentTimeProperty().addListener(new ChangeListener() {
                @Override
                public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                    Duration newDuration = (Duration) newValue;
                    progressBar.setValue((int) Math.round(newDuration.toSeconds()));
                    updateTimeLabel();
                }
            });
            mediaPlayer.setOnReady(new Runnable() {
                public void run() {
                    playerReady = true;
                    progressBar.setMinimum(0.0);
                    progressBar.setValue(0.0);
                    progressBar.setMaximum(mediaPlayer.getTotalDuration().toSeconds());
                    refreshLayout();
                }
            });
            mediaPlayer.setOnError(new Runnable() {
                public void run() {
                    processError(mediaPlayer.getError());
                }
            });
            return mediaPlayer;
        }
        else {
            processError(mediaPlayer.getError());
        }
    }
    catch(Exception e) {
        processError(e);
    }
    return null;
}