javafx.application.Platform Java Examples

The following examples show how to use javafx.application.Platform. 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: NoticeDialog.java    From Quelea with 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 #2
Source File: AlarmAreaInstance.java    From phoebus with 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 File: JavaFXComboBoxTest.java    From marathonv5 with 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 File: TrendChartController.java    From OEE-Designer with 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 File: CurlyApp.java    From curly with 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 File: GrpcResponseHeaderAspectEditor.java    From milkman with 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 File: BlockAndReplacePackets.java    From G-Earth with 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 File: TestRunner.java    From marathonv5 with 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 File: ThemeViewImpl.java    From oim-fx with 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 File: TransactionTypeNodeProvider.java    From constellation with 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
Source File: ControlsPanel.java    From DeskChan with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 File: PhoebusApplication.java    From phoebus with 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 #13
Source File: MainController.java    From cate with 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 #14
Source File: ChatListViewImpl.java    From oim-fx with 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 #15
Source File: Route.java    From FXMaps with 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 #16
Source File: JFXUtilities.java    From JFoenix with 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 #17
Source File: FileRecoveryUILoader.java    From PeerWasp with 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 #18
Source File: AdvancedMedia.java    From netbeans with 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 #19
Source File: NewAttributeCommand.java    From megan-ce with 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 #20
Source File: MapPane.java    From FXMaps with 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 #21
Source File: PCGenPreloader.java    From pcgen with 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 #22
Source File: ConfigureComponentAction.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** @param node Node to position dialog
 *  @param model Model where new component is added
 *  @param item Parent item in alarm tree
 */
public ConfigureComponentAction(final Node node, final AlarmClient model, final AlarmTreeItem<?> item)
{
    super("Configure Item", ImageCache.getImageView(AlarmSystem.class, "/icons/configure.png"));
    setOnAction(event -> Platform.runLater(() ->
    {
        final ItemConfigDialog dialog = new ItemConfigDialog(model, item);
        DialogHelper.positionDialog(dialog, node, -250, -400);
        // Show dialog, not waiting for it to close with OK or Cancel
        dialog.show();
    }));
}
 
Example #23
Source File: StringTable.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void fillToolbar()
{
    toolbar.getItems().addAll(
        createToolbarButton("add_row", Messages.AddRow, event -> addRow()),
        createToolbarButton("remove_row", Messages.RemoveRow, event -> deleteRow()),
        createToolbarButton("row_up", Messages.MoveRowUp, event -> moveRowUpDown(true)),
        createToolbarButton("row_down", Messages.MoveRowDown, event -> moveRowUpDown(false)),
        createToolbarButton("rename_col", Messages.RenameColumn, event -> renameColumn()),
        createToolbarButton("add_col", Messages.AddColumn, event -> addColumn()),
        createToolbarButton("remove_col", Messages.RemoveColumn, event -> deleteColumn()),
        createToolbarButton("col_left", Messages.MoveColumnLeft, event -> moveColumnLeftRight(true)),
        createToolbarButton("col_right", Messages.MoveColumnRight, event -> moveColumnLeftRight(false)));
    Platform.runLater(toolbar::layout);
}
 
Example #24
Source File: FFmpegConvertMediaFilesController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
@Override
public void updateFileProgress(long number, long total) {
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            double p = (number * 1d) / total;
            String s = DateTools.showSeconds(number / 1000) + "/"
                    + DateTools.showSeconds(total / 1000);
            progressBar.setProgress(p);
            progressValue.setText(s);
        }
    });
}
 
Example #25
Source File: LoggerController.java    From G-Earth with MIT License 5 votes vote down vote up
public void onParentSet(){
    getHConnection().getStateObservable().addListener((oldState, newState) -> Platform.runLater(() -> {
        if (newState == HState.PREPARING) {
            miniLogText(Color.ORANGE, "Connecting to "+getHConnection().getDomain() + ":" + getHConnection().getServerPort());
        }
        if (newState == HState.CONNECTED) {
            miniLogText(Color.GREEN, "Connected to "+getHConnection().getDomain() + ":" + getHConnection().getServerPort());
            packetLogger.start();
        }
        if (newState == HState.NOT_CONNECTED) {
            miniLogText(Color.RED, "End of connection");
            packetLogger.stop();
        }
    }));

    getHConnection().addTrafficListener(2, message -> { Platform.runLater(() -> {
        if (message.getDestination() == HMessage.Direction.TOCLIENT && cbx_blockIn.isSelected() ||
                message.getDestination() == HMessage.Direction.TOSERVER && cbx_blockOut.isSelected()) return;

        if (cbx_splitPackets.isSelected()) {
            packetLogger.appendSplitLine();
        }

        int types = 0;
        if (message.getDestination() == HMessage.Direction.TOCLIENT) types |= PacketLogger.MESSAGE_TYPE.INCOMING.getValue();
        else if (message.getDestination() == HMessage.Direction.TOSERVER) types |= PacketLogger.MESSAGE_TYPE.OUTGOING.getValue();
        if (message.getPacket().length() >= packetLimit) types |= PacketLogger.MESSAGE_TYPE.SKIPPED.getValue();
        if (message.isBlocked()) types |= PacketLogger.MESSAGE_TYPE.BLOCKED.getValue();
        if (message.getPacket().isReplaced()) types |= PacketLogger.MESSAGE_TYPE.REPLACED.getValue();
        if (cbx_showAdditional.isSelected()) types |= PacketLogger.MESSAGE_TYPE.SHOW_ADDITIONAL_DATA.getValue();

        packetLogger.appendMessage(message.getPacket(), types);

        if (cbx_showstruct.isSelected() && message.getPacket().length() < packetLimit) {
            packetLogger.appendStructure(message.getPacket());
        }
    });
    });
}
 
Example #26
Source File: DisplayWindow.java    From marathonv5 with 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 #27
Source File: LBTextTab.java    From PDF4Teachers with Apache License 2.0 5 votes vote down vote up
public void selectItem(){
	new Thread(() -> {
		try{
			Thread.sleep(50);
			Platform.runLater(() -> {
				String text = txtArea.getText();
				txtArea.setText(text);
				txtArea.positionCaret(txtArea.getText().length());
				txtArea.requestFocus();
			});
		}catch(InterruptedException e){ e.printStackTrace();}
	}, "selector").start();

}
 
Example #28
Source File: ScanMonitor.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void connectionError()
{
    Platform.runLater(() ->
    {
        scans.update(Collections.emptyList());
        scans.update((ScanServerInfo) null);
    });
}
 
Example #29
Source File: LoginViewImpl.java    From oim-fx with 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 #30
Source File: JavaFXSpinnerElementTest.java    From marathonv5 with 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;
        }
    };
}