Java Code Examples for javafx.application.Platform

The following examples show how to use javafx.application.Platform. These examples are extracted from open source projects. 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 Project: pcgen   Source File: PCGenPreloader.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public PCGenPreloader()
{
	GuiAssertions.assertIsNotOnGUIThread();
	loader.setLocation(getClass().getResource("PCGenPreloader.fxml"));
	Platform.runLater(() -> {
		primaryStage = new Stage();
		final Scene scene;
		try
		{
			scene = loader.load();
		} catch (IOException e)
		{
			Logging.errorPrint("failed to load preloader", e);
			return;
		}

		primaryStage.setScene(scene);
		primaryStage.show();
	});
}
 
Example 2
Source Project: phoebus   Source File: AlarmAreaInstance.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void changeConfig(final String new_config_name)
{
    // Dispose existing setup
    dispose();

    try
    {
        // Use same server name, but new config_name
        final URI new_input = AlarmURI.createURI(server, new_config_name);
        tab.setContent(create(new_input));
        tab.setInput(new_input);
        Platform.runLater(() -> tab.setLabel(config_name + " " + app.getDisplayName()));
    }
    catch (Exception ex)
    {
        logger.log(Level.WARNING, "Cannot switch alarm area panel to " + config_name, ex);
    }
}
 
Example 3
Source Project: marathonv5   Source File: JavaFXComboBoxTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void selectDuplicateOption() {
    @SuppressWarnings("unchecked")
    ComboBox<String> comboNode = (ComboBox<String>) getPrimaryStage().getScene().getRoot().lookup(".combo-box");
    IJavaFXElement comboBox = combos.get(0);
    Platform.runLater(() -> {
        comboNode.getItems().add(3, "Option 2");
        comboBox.marathon_select("Option 2(1)");
    });
    new Wait("Waiting for combo box option to be set.") {
        @Override
        public boolean until() {
            return comboNode.getSelectionModel().getSelectedIndex() == 3;
        }
    };
}
 
Example 4
Source Project: OEE-Designer   Source File: TrendChartController.java    License: MIT License 6 votes vote down vote up
private void plotData(final Object inputValue, final Object plottedValue) throws Exception {
	if (inputValue == null) {
		return;
	}

	Platform.runLater(() -> {
		// plot output value
		if (plottedValue != null) {
			if (plottedValue instanceof String) {
				outputValueController.plotValue((String) plottedValue);
			} else if (plottedValue instanceof Number) {
				outputValueController.plotValue((Number) plottedValue);
			}
		}

		// plot input value
		if (inputValue instanceof Number) {
			inputValueController.plotValue((Number) inputValue);
		} else if (inputValue instanceof Boolean) {
			int intValue = (Boolean) inputValue ? 1 : 0;
			inputValueController.plotValue(intValue);
		} else if (inputValue instanceof String) {
			inputValueController.plotValue((String) inputValue);
		}
	});
}
 
Example 5
Source Project: curly   Source File: CurlyApp.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start(Stage stage) throws Exception {
    applicationWindow = stage;
    Locale locale = Locale.US;
    ApplicationState.getInstance().setResourceBundle(ResourceBundle.getBundle("Bundle", locale));
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/App.fxml"));
    loader.setResources(ApplicationState.getInstance().getResourceBundle());
    loader.load();
    Parent root = loader.getRoot();
    appController = loader.getController();

    Scene scene = new Scene(root);
    scene.getStylesheets().add("/styles/Styles.css");

    stage.setTitle(ApplicationState.getInstance().getResourceBundle().getString(APPLICATION_TITLE));
    stage.setScene(scene);
    stage.show();

    stage.setOnCloseRequest(event -> {
        ConnectionManager.getInstance().shutdown();
        Platform.exit();
        System.exit(0);
    });
}
 
Example 6
Source Project: milkman   Source File: GrpcResponseHeaderAspectEditor.java    License: MIT License 6 votes vote down vote up
@Override
@SneakyThrows
public Tab getRoot(RequestContainer request, ResponseContainer response) {
	GrpcResponseHeaderAspect headers = response.getAspect(GrpcResponseHeaderAspect.class).get();
	JfxTableEditor<HeaderEntry> editor = new JfxTableEditor<HeaderEntry>();
	editor.disableAddition();
	editor.addReadOnlyColumn("Name", HeaderEntry::getName);
	editor.addReadOnlyColumn("Value", HeaderEntry::getValue);
	editor.setRowToStringConverter(this::headerToString);
	
	headers.getEntries().thenAccept(headerList -> {Platform.runLater(() -> {
			editor.setItems(headerList);	
		});
	});
	
	
	return new Tab("Response Headers", editor);
}
 
Example 7
Source Project: G-Earth   Source File: BlockAndReplacePackets.java    License: MIT License 6 votes vote down vote up
public void initialize() {
    cmb_type.getItems().addAll("Block packet", "Replace packet", "Replace integer", "Replace string", "Replace substring");
    cmb_type.getSelectionModel().selectFirst();

    cmb_side.getItems().addAll("Incoming", "Outgoing");
    cmb_side.getSelectionModel().selectFirst();

    cmb_side.getSelectionModel().selectedItemProperty().addListener(observable -> Platform.runLater(this::refreshOptions));
    cmb_type.getSelectionModel().selectedItemProperty().addListener(observable -> Platform.runLater(this::refreshOptions));
    txt_replacement.textProperty().addListener(event -> Platform.runLater(this::refreshOptions));
    txt_value.textProperty().addListener(event -> Platform.runLater(this::refreshOptions));

    refreshOptions();
    cmb_type.requestFocus();

}
 
Example 8
Source Project: marathonv5   Source File: TestRunner.java    License: Apache License 2.0 6 votes vote down vote up
private void resetToolBar() {
    Runnable doRun = new Runnable() {
        @Override
        public void run() {
            nextFailureAction.setEnabled(mode == Mode.RESULTS);
            prevFailureAction.setEnabled(mode == Mode.RESULTS);
            failuresToggleButton.setDisable(!(mode == Mode.RESULTS));
            boolean selected = failuresToggleButton.isSelected();
            failuresToggleButton.setSelected(selected && mode == Mode.RESULTS);
            stopAction.setEnabled(mode == Mode.RUNNING);
            reportAction.setEnabled(mode == Mode.RESULTS);
            runAction.setEnabled(mode != Mode.RUNNING && historyMenuItems.size() > 0);
            runSelected.setEnabled(mode != Mode.RUNNING && testTree.getSelectionModel().getSelectedItems().size() > 0);
        }
    };
    if (Platform.isFxApplicationThread()) {
        doRun.run();
    } else {
        Platform.runLater(doRun);
    }
}
 
Example 9
Source Project: oim-fx   Source File: ThemeViewImpl.java    License: MIT License 6 votes vote down vote up
public ThemeViewImpl(AppContext appContext) {
	super(appContext);
	Platform.runLater(new Runnable() {
		@Override
		public void run() {
			themeStage = new ThemeStage();
			initEvent();
		}
	});
	Task<Integer> task = new Task<Integer>() {
		@Override
		protected Integer call() throws Exception {
			int iterations = 0;
			initData();
			return iterations;
		}
	};
	Thread th = new Thread(task);
	th.setDaemon(true);
	th.start();
}
 
Example 10
Source Project: constellation   Source File: TransactionTypeNodeProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void newActiveGraph(final Graph graph) {
    // TODO: if the old graph and the new graph have the same schema, don't recalculate.
    Platform.runLater(() -> {
        detailsView.getChildren().clear();
        final Label nameLabel = new Label("No type selected");
        detailsView.getChildren().add(nameLabel);

        transactionTypes.clear();

        if (graph != null && graph.getSchema() != null && GraphNode.getGraphNode(graph) != null) {
            final SchemaFactory schemaFactory = graph.getSchema().getFactory();
            final Set<Class<? extends SchemaConcept>> concepts = schemaFactory.getRegisteredConcepts();
            schemaLabel.setText(String.format("%s - %s", schemaFactory.getLabel(), GraphNode.getGraphNode(graph).getDisplayName()));
            transactionTypes.addAll(SchemaTransactionTypeUtilities.getTypes(concepts));
            Collections.sort(transactionTypes, (final SchemaTransactionType a, final SchemaTransactionType b) -> a.getName().compareToIgnoreCase(b.getName()));

        } else {
            schemaLabel.setText("No schema available");
        }
        populateTree();
    });
}
 
Example 11
public void hide(){
	ControlsPanel currentPanel = registeredPanels.get(getFullName());
	if (currentPanel == null) {
		set();
		currentPanel = this;
	}

	switch (currentPanel.type){
		case WINDOW:{
			Platform.runLater(() -> ControlsWindow.closeCustomWindow(this));
		} break;
		case TAB: case SUBMENU: case PANEL:{
			OptionsDialog.showPanel(null);
		} break;
	}
}
 
Example 12
Source Project: FXMaps   Source File: MapPane.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Called internally to configure size, position and style of the overlay.
 */
private void configureOverlay() {
    dimmer = new StackPane();
    dimmer.setManaged(false);
    dimmerMessage = new Label(DEFAULT_OVERLAY_MESSAGE);
    dimmerMessage.setFont(Font.font(dimmerMessage.getFont().getFamily(), FontWeight.BOLD, 18));
    dimmerMessage.setTextFill(Color.WHITE);
    dimmer.getChildren().add(dimmerMessage);
    dimmer.setStyle("-fx-background-color: rgba(0, 0, 0, 0.6);");
    getChildren().add(dimmer);
    
    layoutBoundsProperty().addListener((v, o, n) -> {
        Platform.runLater(() -> {
            if(MapPane.this.getScene().getWindow() == null) return;
            Point2D mapPoint = contentPane.localToParent(0, 0);
            double topHeight = contentPane.getTop() == null ? 0 : contentPane.getTop().getLayoutBounds().getHeight();
            dimmer.resizeRelocate(mapPoint.getX(), mapPoint.getY() + topHeight, 
                contentPane.getWidth(), contentPane.getHeight() - topHeight);
        });
    });
}
 
Example 13
Source Project: phoebus   Source File: PhoebusApplication.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/** @param memento Memento for new layout that should replace current one */
private void replaceLayout(final MementoTree memento)
{
    final List<Stage> stages = DockStage.getDockStages();

    // To switch layout, 'fixed' panes must be cleared
    for (Stage stage : stages)
        DockStage.clearFixedPanes(stage);

    // Remove the main stage from the list of stages to close.
    stages.remove(main_stage);

    // If any stages failed to close, return.
    if (!closeStages(stages))
        return;

    // Go into the main stage and close all of the tabs. If any of them refuse, return.
    final Node node = DockStage.getPaneOrSplit(main_stage);
    if (! MementoHelper.closePaneOrSplit(node))
        return;

    // Allow handlers for tab changes etc. to run as everything closed.

    // On next UI tick, load content from memento file.
    Platform.runLater(() -> restoreState(memento));
}
 
Example 14
Source Project: cate   Source File: MainController.java    License: MIT License 6 votes vote down vote up
/**
 * Show a top banner with a 3 second timeout and the specified text. Must
 * be called from the UI thread.
 *
 * @param text Text to show in the banner.
 */
private void showTopBannerOnUIThread(String text) {
    notificationPane.setText(text);
    notificationPane.getStyleClass().add(NotificationPane.STYLE_CLASS_DARK);
    notificationPane.show();
    // TODO: We should have a single persistent thread that does this, and
    // handles resetting the timer if a new banner is shown before the old is
    // hidden
    new Thread(() -> {
        try {
            Thread.sleep(BANNER_DISPLAY_MILLIS);
        } catch (InterruptedException ex) {
            // Ignore
        }
        Platform.runLater(() -> {
            notificationPane.hide();
        });
    }).start();
}
 
Example 15
Source Project: oim-fx   Source File: ChatListViewImpl.java    License: MIT License 6 votes vote down vote up
@Override
public void show(Group group) {
	String groupId = group.getId();
	String key = this.createKey("group", groupId);

	ChatListItemContext itemContext = appContext.getObject(ChatListItemContext.class);
	ChatListPaneContext paneContext = appContext.getObject(ChatListPaneContext.class);

	ChatItem chatItem = itemContext.getGroupChatItem(group);
	ChatPane cp = paneContext.getGroupChatPane(group);
	
	Platform.runLater(new Runnable() {
		@Override
		public void run() {
			chatListStage.addItem(key, chatItem, cp);
			chatListStage.selected(key);
			
			ListRootPane listPane=getGroupUserListRootPane(groupId);
			cp.setRight(listPane);
		}
	});
}
 
Example 16
Source Project: FXMaps   Source File: Route.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void createUnderlying() {
    // If deserializing in non-headless mode, build javascript peers
    if(Platform.isFxApplicationThread()) {
        if(origin == null || origin.getMarker() == null) {
            throw new NullPointerException("Route had malformed origin");
        }
        
        origin.getMarker().createUnderlying();
        destination.getMarker().createUnderlying();
        for(Waypoint wp : observableDelegate) {
            wp.getMarker().createUnderlying();
        }
        
        for(Polyline line : lines) {
            line.createUnderlying();
        }
    }
}
 
Example 17
Source Project: JFoenix   Source File: JFXUtilities.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to run a specified Runnable in the FX Application thread,
 * it waits for the task to finish before returning to the main thread.
 *
 * @param doRun This is the sepcifed task to be excuted by the FX Application thread
 * @return Nothing
 */
public static void runInFXAndWait(Runnable doRun) {
    if (Platform.isFxApplicationThread()) {
        doRun.run();
        return;
    }
    final CountDownLatch doneLatch = new CountDownLatch(1);
    Platform.runLater(() -> {
        try {
            doRun.run();
        } finally {
            doneLatch.countDown();
        }
    });
    try {
        doneLatch.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
 
Example 18
Source Project: PeerWasp   Source File: FileRecoveryUILoader.java    License: MIT License 6 votes vote down vote up
private static void showError(final String message) {
	Runnable dialog = new Runnable() {
		@Override
		public void run() {
			Alert dlg = DialogUtils.createAlert(AlertType.ERROR);
			dlg.setTitle("Error Recovering File.");
			dlg.setHeaderText("Could not recover file.");
			dlg.setContentText(message);
			dlg.showAndWait();
		}
	};

	if (Platform.isFxApplicationThread()) {
		dialog.run();
	} else {
		Platform.runLater(dialog);
	}
}
 
Example 19
Source Project: netbeans   Source File: AdvancedMedia.java    License: Apache License 2.0 6 votes vote down vote up
protected void updateValues() {
    if (playTime != null && timeSlider != null && volumeSlider != null && duration != null) {
        Platform.runLater(new Runnable() {
            public void run() {
                Duration currentTime = mp.getCurrentTime();
                playTime.setText(formatTime(currentTime, duration));
                timeSlider.setDisable(duration.isUnknown());
                if (!timeSlider.isDisabled() && duration.greaterThan(Duration.ZERO) && !timeSlider.isValueChanging()) {
                    timeSlider.setValue(currentTime.divide(duration).toMillis() * 100.0);
                }
                if (!volumeSlider.isValueChanging()) {
                    volumeSlider.setValue((int) Math.round(mp.getVolume() * 100));
                }
            }
        });
    }
}
 
Example 20
Source Project: megan-ce   Source File: NewAttributeCommand.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void actionPerformed(ActionEvent event) {
    final SamplesViewer viewer = ((SamplesViewer) getViewer());
    final int index;
    final String selectedAttribute = viewer.getSamplesTableView().getASelectedAttribute();
    if (selectedAttribute != null)
        index = viewer.getSamplesTableView().getAttributes().indexOf(selectedAttribute);
    else
        index = viewer.getSamplesTableView().getSampleCount();

    String name = null;
    if (Platform.isFxApplicationThread()) {
        TextInputDialog dialog = new TextInputDialog("Attribute");
        dialog.setTitle("New attribute");
        dialog.setHeaderText("Enter attribute name:");

        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()) {
            name = result.get().trim();
        }
    } else if (javax.swing.SwingUtilities.isEventDispatchThread()) {
        name = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter new attribute name", "Untitled");
    }

    if (name != null)
        executeImmediately("new attribute='" + name + "' position=" + index + ";");
}
 
Example 21
Source Project: Quelea   Source File: NoticeDialog.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Read the stored notice files and add them to the list.
 */
private void getNoticesFromFile() {
    noticeTemplates = new ListView<>();
    final File[] files = new File(QueleaProperties.get().getNoticeDir().getAbsolutePath()).listFiles();
    if (noticeTemplatesUpdateThread != null && noticeTemplatesUpdateThread.isAlive()) {
        return;
    }
    noticeTemplatesUpdateThread = new Thread() {
        @Override
        public void run() {
            if (files != null) {
                for (final File file : files) {
                    Platform.runLater(() -> {
                        Notice n = NoticeFileHandler.noticeFromFile(file);
                        if (n != null) {
                            noticeTemplates.getItems().add(n);
                        }
                    });
                }
            }
        }
    };
    noticeTemplatesUpdateThread.start();
}
 
Example 22
Source Project: marathonv5   Source File: JavaFXTreeViewElementTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void marathon_select_multiple() throws Throwable {
    TreeView<?> treeViewNode = (TreeView<?>) getPrimaryStage().getScene().getRoot().lookup(".tree-view");
    treeViewNode.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    Platform.runLater(() -> treeView.marathon_select("[\"/Root node/Child Node 1\",\"/Root node/Child Node 3/Child Node 7\"]"));
    new Wait("Waiting for the text item to be selected.") {
        @Override
        public boolean until() {
            return 2 == treeViewNode.getSelectionModel().getSelectedIndices().size();
        }
    };
}
 
Example 23
Source Project: phoebus   Source File: LogbookSearchController.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void search(Map<String, String> map) {
    if (logbookSearchJob != null) {
        logbookSearchJob.cancel();
    }
    logbookSearchJob = LogbookSearchJob.submit(this.client,
            map,
            logs -> Platform.runLater(() -> setLogs(logs)),
            (url, ex) -> ExceptionDetailsErrorDialog.openError("Logbook Search Error", ex.getMessage(), ex));
}
 
Example 24
Source Project: MyBox   Source File: DataExportController.java    License: Apache License 2.0 5 votes vote down vote up
protected void writeExternalCSVTask(String filePrefix, String sql) {
    File file = new File(filePrefix + ".csv");
    Platform.runLater(() -> {
        synchronized (this) {
            ++taskCount;
        }
        String filename = file.getAbsolutePath();
        updateLogs(message("Exporting") + " " + filename);
        BaseTask dTask = new BaseTask<Void>() {
            @Override
            protected boolean handle() {
                return writeExternalCSV(file, sql);
            }

            @Override
            protected void whenSucceeded() {
                if (!cancelled) {
                    updateLogs(message("Generated") + "." + file.getAbsolutePath());
                }
            }

            @Override
            protected void finalAction() {
                checkFinished();
            }

        };
        Thread thread = new Thread(dTask);
        thread.setDaemon(true);
        thread.start();
    });
}
 
Example 25
Source Project: curly   Source File: CurlyApp.java    License: Apache License 2.0 5 votes vote down vote up
public static void runNow(Runnable r) {
    if (Platform.isFxApplicationThread()) {
        r.run();
    } else {
        Semaphore s = new Semaphore(0);
        Platform.runLater(()->{
            r.run();
            synchronized (s) {
                s.release();
            }
        });
        s.acquireUninterruptibly();
    }
}
 
Example 26
Source Project: oim-fx   Source File: LoginViewImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void setVisible(boolean visible) {
	Platform.runLater(new Runnable() {
		@Override
		public void run() {
			if (visible) {
				loginFrame.show();
			} else {
				loginFrame.hide();
			}
		}
	});
}
 
Example 27
Source Project: marathonv5   Source File: DisplayWindow.java    License: Apache License 2.0 5 votes vote down vote up
private void setState() {
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            displayView.setState(state);
        }
    });
}
 
Example 28
Source Project: marathonv5   Source File: JavaFXSpinnerElementTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void selectIntegerSpinner() {
    IJavaFXElement spinner = driver.findElementByName("integer-spinner");
    Spinner<?> spinnerNode = (Spinner<?>) getPrimaryStage().getScene().getRoot().lookup("#integer-spinner");
    Platform.runLater(() -> {
        spinner.marathon_select("35");
    });
    new Wait("Waiting for spinner to set value") {
        @Override
        public boolean until() {
            Integer value = (Integer) spinnerNode.getValue();
            return value == 35;
        }
    };
}
 
Example 29
@Override
public void onTick(long ticks) {
    Platform.runLater(() -> {
        boolean text = machine.getSwitches().get(0);
        if (text) {
            showText(segmentMem.getText(), (byte) ~0);
        } else {
            showGraph(segmentMem.getGraphLow(), segmentMem.getGraphHigh());
        }
    });
}
 
Example 30
Source Project: SubTitleSearcher   Source File: ExtractDialog.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * 打开网址
	 * 
	 * @param url
	 */
	private void openUrl(String url) {
		com.sun.javafx.webkit.WebConsoleListener.setDefaultListener((webView, message, lineNumber, sourceId) -> {
			logger.info("from webview: " + message + " [" + sourceId + " - " + lineNumber + "]");
		});
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				
				
				webview = new WebView();
				// webview.setContextMenuEnabled(false);

				WebEngine webEngine = webview.getEngine();

				webEngine.setJavaScriptEnabled(true);
				webEngine.setOnAlert(event -> jsAlert(event.getData()));
				webEngine.setConfirmHandler(message -> jsConfirm(message));

				webEngine.setOnError(event -> {
					logger.info(event.getMessage());
				});
//				webEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
//					
//				});
				
				webviewScene = new Scene(webview);
				bsPanel.setScene(webviewScene);
				
				initData();
				webEngine.load(url);
				webview.getEngine().executeScript("window.serverPort="+AppConfig.serverPort+"");
				
			}
		});
	}