List of usage examples for javafx.concurrent Task Task
public Task()
From source file:editeurpanovisu.EquiCubeDialogController.java
public Task tskTraitement() { return new Task() { @Override//from w w w.j a va 2 s . c o m protected Object call() throws Exception { apTransformations.setCursor(Cursor.WAIT); Platform.runLater(() -> { for (int ij = 0; ij < lvListeFichier.getItems().size(); ij++) { String strNomFich1 = (String) lvListeFichier.getItems().get(ij); lvListeFichier.getItems().set(ij, "A Traiter => " + strNomFich1); } }); updateProgress(0.0001f, lvListeFichier.getItems().size()); for (int i1 = 0; i1 < lvListeFichier.getItems().size(); i1++) { Thread.sleep(200); updateMessage("Traitement en cours " + (i1 + 1) + "/" + lvListeFichier.getItems().size()); String strNomFich = ((String) lvListeFichier.getItems().get(i1)).split("> ")[1]; final int ii = i1; Platform.runLater(() -> { lvListeFichier.getItems().set(ii, "Traitement en cours => " + strNomFich); }); traiteFichier(strNomFich, i1); Thread.sleep(100); updateProgress(i1 + 1, lvListeFichier.getItems().size()); Platform.runLater(() -> { lvListeFichier.getItems().set(ii, "Trait => " + strNomFich); }); Thread.sleep(100); } apTransformations.setCursor(Cursor.DEFAULT); return true; } @Override protected void succeeded() { super.succeeded(); pbBarreAvancement.progressProperty().unbind(); lblTermine.textProperty().unbind(); lblTermine.setText("Traitement Termin"); pbBarreAvancement.setProgress(0.001d); pbBarreAvancement.setVisible(false); pbBarreImage.setVisible(false); bTraitementEffectue = true; lblDragDropE2C.setVisible(true); } }; }
From source file:frontend.GUIController.java
public Thread processInput(Runnable rSuccess, Runnable rFail) throws Exception { System.out.println("Steping to next step..."); progressBar.progressProperty().unbind(); progressMessage.textProperty().unbind(); next1.setDisable(true);//from w ww. j a v a2 s . c o m final ArrayList<String> comboBoxValues = new ArrayList<String>(); for (ComboBox<String> c : comboBoxes) { comboBoxValues.add(c.getValue()); } Task<Boolean> t = new Task<Boolean>() { @Override protected Boolean call() throws Exception { updateMessage("Doing Prediction"); updateProgress(3, 10); int status = at.processAfterLoadFile(comboBoxValues, predModel.getValue(), visualize.isSelected(), predicted.isSelected()); if (status > 0) { System.err.println("ProcessAfterLoadFile Error occured."); return false; } updateMessage("Finished Prediction"); if (visualize.isSelected()) { updateProgress(5, 10); at.showVisualization(); updateMessage("Finished Visualization"); updateProgress(8, 10); } updateProgress(10, 10); updateMessage("Done"); //webpage.getChildren().add(new Browser(url)); //at.addTweets(at.outputDir+"/visualization/Sentiment.tsv", personData); return true; }; @Override protected void succeeded() { super.succeeded(); updateMessage("Done!"); } @Override protected void cancelled() { super.cancelled(); updateMessage("Cancelled!"); } @Override protected void failed() { super.failed(); updateMessage("Failed!"); } @Override protected void done() { super.done(); updateMessage("Done!"); } }; progressBar.progressProperty().bind(t.progressProperty()); progressMessage.textProperty().bind(t.messageProperty()); t.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent event) { if (t.getValue()) { Platform.runLater(rSuccess); } else { Platform.runLater(rFail); } } }); Thread mythread = new Thread(t); mythread.start(); return mythread; }
From source file:genrsa.GenRSAController.java
/** * Mtodo usado cuando se pulsa el boton de generar de manera automtica una clave * @param event /*from w w w . j a va2 s .c o m*/ */ public void processAutomaticGeneration(ActionEvent event) { if (this.startGenKey) { Task CAstart = new Task() { @Override protected Object call() throws Exception { startGenKey = false; String keySize = bits_clave_automatica.getText(); boolean isSameSize = sameSizePrimes.isSelected(); boolean isTipicalPubKey = tipicalPubKey.isSelected(); boolean isSecurePrimes = securePrimes.isSelected(); progress.setVisible(true); Platform.runLater(() -> { disableOnProgress(true); configureGenKeyStop(true); }); RSA = generate.autoRSAkeys(keySize, isSameSize, isTipicalPubKey, isSecurePrimes); Platform.runLater(() -> { disableOnProgress(false); configureGenKeyStop(false); mainWindow.clearPrimality(); disableButtons(); configureGenKeyButtons(isTipicalPubKey, keySize); }); progress.setVisible(false); startGenKey = true; return null; } }; new Thread(CAstart).start(); } else { this.autoGenerarBttn.setDisable(true); this.generate.setGenKeyCancelled(); this.mainWindow.delete(); this.startGenKey = true; } }
From source file:com.jscriptive.moneyfx.ui.chart.ChartFrame.java
public void yearlyInOutToggled(ActionEvent actionEvent) { final NumberAxis xAxis = new NumberAxis(); final CategoryAxis yAxis = new CategoryAxis(); yAxis.setLabel("In/Out in Euro"); xAxis.setLabel("Year"); final BarChart<Number, String> barChart = new BarChart<>(xAxis, yAxis); barChart.setTitle("Yearly in/out"); chartFrame.setCenter(barChart);//from w w w. ja va 2 s . c om ToggleButton toggle = (ToggleButton) actionEvent.getTarget(); if (toggle.isSelected()) { Account account = accountCombo.getValue(); String accountLabel = getAccountLabel(account); XYChart.Series<Number, String> inSeries = new XYChart.Series<>(); inSeries.setName("In" + accountLabel); barChart.getData().add(inSeries); XYChart.Series<Number, String> outSeries = new XYChart.Series<>(); outSeries.setName("Out" + accountLabel); barChart.getData().add(outSeries); ValueRange<LocalDate> period = getTransactionOpRange(account, yearCombo.getValue()); if (period.isEmpty()) { return; } ObservableList<String> categories = FXCollections.observableArrayList(); for (int y = period.from().getYear(); y < period.to().getYear() + 6; y++) { categories.add(String.valueOf(y)); } yAxis.setCategories(categories); Service<Void> service = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { List<TransactionVolume> incomingVolumes = (account == ALL_ACCOUNTS) ? transactionRepository.getYearlyIncomingVolumes(false) : transactionRepository.getYearlyIncomingVolumesOfAccount(account, false); if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) { incomingVolumes = incomingVolumes.stream() .filter(v -> v.getYear().equals(yearCombo.getValue())) .sorted((v1, v2) -> v1.getDate().compareTo(v2.getDate())).collect(toList()); } for (TransactionVolume volume : incomingVolumes) { XYChart.Data<Number, String> inData = new XYChart.Data<>(volume.getVolume(), String.valueOf(volume.getYear())); Platform.runLater(() -> { inSeries.getData().add(inData); StackPane node = (StackPane) inData.getNode(); node.getChildren().add( new Label(CurrencyFormat.getInstance().format(volume.getVolume()))); node.addEventHandler(MOUSE_CLICKED, event -> handleYearlyInOutChartMouseClickEvent( (account == ALL_ACCOUNTS) ? null : account, ofYearDay(volume.getYear(), 1), event)); }); } List<TransactionVolume> outgoingVolumes = (account == ALL_ACCOUNTS) ? transactionRepository.getYearlyOutgoingVolumes(false) : transactionRepository.getYearlyOutgoingVolumesOfAccount(account, false); if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) { outgoingVolumes = outgoingVolumes.stream() .filter(v -> v.getYear().equals(yearCombo.getValue())) .sorted((v1, v2) -> v1.getDate().compareTo(v2.getDate())).collect(toList()); } for (TransactionVolume volume : outgoingVolumes) { XYChart.Data<Number, String> outData = new XYChart.Data<>(volume.getVolume().abs(), String.valueOf(volume.getYear())); Platform.runLater(() -> { outSeries.getData().add(outData); StackPane node = (StackPane) outData.getNode(); node.getChildren().add( new Label(CurrencyFormat.getInstance().format(volume.getVolume()))); node.addEventHandler(MOUSE_CLICKED, event -> handleYearlyInOutChartMouseClickEvent( (account == ALL_ACCOUNTS) ? null : account, ofYearDay(volume.getYear(), 1), event)); }); } return null; } }; } }; service.start(); } }
From source file:com.QuarkLabs.BTCeClientJavaFX.MainController.java
@FXML void initialize() { assert clearLogButton != null : "fx:id=\"clearLogButton\" was not injected: check your FXML file 'mainlayout.fxml'."; assert fundsTable != null : "fx:id=\"fundsTable\" was not injected: check your FXML file 'mainlayout.fxml'."; assert logField != null : "fx:id=\"logField\" was not injected: check your FXML file 'mainlayout.fxml'."; assert buyButton != null : "fx:id=\"buyButton\" was not injected: check your FXML file 'mainlayout.fxml'."; assert sellButton != null : "fx:id=\"sellButton\" was not injected: check your FXML file 'mainlayout.fxml'."; assert showActiveOrdersButton != null : "fx:id=\"showActiveOrdersButton\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tickersTableLastColumn != null : "fx:id=\"tickerTableLastColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tickersTablePairColumn != null : "fx:id=\"tickerTablePairColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tickersTable != null : "fx:id=\"tickersTable\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tickersTableBuyColumn != null : "fx:id=\"tickersTableBuyColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tickersTableFeeColumn != null : "fx:id=\"tickersTableFeeColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tickersTableSellColumn != null : "fx:id=\"tickersTableSellColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tradeAmountValue != null : "fx:id=\"tradeAmountValue\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tradePriceCurrencyType != null : "fx:id=\"tradeCurrencyPriceValue\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tradeCurrencyType != null : "fx:id=\"tradeCurrencyType\" was not injected: check your FXML file 'mainlayout.fxml'."; assert tradePriceValue != null : "fx:id=\"tradePriceValue\" was not injected: check your FXML file 'mainlayout.fxml'."; assert updateFundsButton != null : "fx:id=\"updateFundsButton\" was not injected: check your FXML file 'mainlayout.fxml'."; assert fundsTableCurrencyColumn != null : "fx:id=\"fundsTableCurrencyColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert fundsTableValueColumn != null : "fx:id=\"fundsTableValueColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert activeOrdersTable != null : "fx:id=\"fundsTableValueColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert activeOrdersAmountColumn != null : "fx:id=\"activeOrdersAmountColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert activeOrdersPairColumn != null : "fx:id=\"activeOrdersPairColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert activeOrdersRateColumn != null : "fx:id=\"activeOrdersRateColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert activeOrdersTimeColumn != null : "fx:id=\"activeOrdersTimeColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert activeOrdersTypeColumn != null : "fx:id=\"activeOrdersTypeColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; assert activeOrdersCancelColumn != null : "fx:id=\"activeOrdersCancelColumn\" was not injected: check your FXML file 'mainlayout.fxml'."; //Holder for all main API methods of exchange app = new App(); //Loading configs loadExchangeConfig();//w w w .j ava 2 s. com //Populate choiceboxes at the trading section tradeCurrencyType.setItems(FXCollections.observableArrayList(currencies)); tradeCurrencyType.setValue(currencies.get(0)); tradePriceCurrencyType.setItems(FXCollections.observableArrayList(currencies)); tradePriceCurrencyType.setValue(currencies.get(0)); //Active Orders table activeOrdersAmountColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, Double>("amount")); activeOrdersPairColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, String>("pair")); activeOrdersRateColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, Double>("rate")); activeOrdersTimeColumn.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<ActiveOrder, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call( TableColumn.CellDataFeatures<ActiveOrder, String> activeOrderStringCellDataFeatures) { ActiveOrder activeOrder = activeOrderStringCellDataFeatures.getValue(); DateFormat dateFormat = DateFormat.getDateTimeInstance(); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(activeOrder.getTimestamp() * 1000); return new SimpleStringProperty(dateFormat.format(calendar.getTime())); } }); activeOrdersTypeColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, String>("type")); activeOrdersTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); activeOrdersCancelColumn .setCellFactory(new Callback<TableColumn<ActiveOrder, Boolean>, TableCell<ActiveOrder, Boolean>>() { @Override public TableCell<ActiveOrder, Boolean> call( TableColumn<ActiveOrder, Boolean> activeOrderBooleanTableColumn) { return new ButtonCell<>(activeOrdersTable); } }); activeOrdersCancelColumn.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<ActiveOrder, Boolean>, ObservableValue<Boolean>>() { @Override public ObservableValue<Boolean> call( TableColumn.CellDataFeatures<ActiveOrder, Boolean> activeOrderBooleanCellDataFeatures) { return new SimpleBooleanProperty(true); } }); //Tickers Table MenuItem showOrdersBook = new MenuItem("Show Orders Book"); MenuItem showPublicTrades = new MenuItem("Show Public Trades"); ContextMenu contextMenu = new ContextMenu(showOrdersBook, showPublicTrades); tickersTable.setItems(tickers); tickersTable.setContextMenu(contextMenu); tickersTableBuyColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("buy")); tickersTableFeeColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("fee")); tickersTableSellColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("sell")); tickersTableLastColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("last")); tickersTablePairColumn.setCellValueFactory(new PropertyValueFactory<Ticker, String>("pair")); tickersTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); tickersTable.setRowFactory(new Callback<TableView<Ticker>, TableRow<Ticker>>() { @Override public TableRow<Ticker> call(TableView<Ticker> tickerTableView) { return new TableRow<Ticker>() { @Override protected void updateItem(Ticker ticker, boolean b) { super.updateItem(ticker, b); if (!b) { if (tickersData.containsKey(ticker.getPair())) { if (ticker.getLast() < tickersData.get(ticker.getPair()).getLast()) { setStyle("-fx-control-inner-background: rgba(186, 0, 0, 0.5);"); } else if (ticker.getLast() == tickersData.get(ticker.getPair()).getLast()) { setStyle("-fx-control-inner-background: rgba(215, 193, 44, 0.5);"); } else { setStyle("-fx-control-inner-background: rgba(0, 147, 0, 0.5);"); } } } } }; } }); //Menu item to show Orders Book showOrdersBook.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { Ticker selectedTicker = tickersTable.getSelectionModel().getSelectedItem(); Parent root; try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_TO_ORDERS_BOOK_LAYOUT), resources); root = (Parent) fxmlLoader.load(); OrdersBookController ordersBookController = fxmlLoader.getController(); ordersBookController.injectPair(selectedTicker.getPair()); Stage stage = new Stage(); stage.setTitle("Orders Book for " + selectedTicker.getPair().replace("_", "/").toUpperCase()); stage.setScene(new Scene(root)); stage.setResizable(false); stage.show(); } catch (IOException e) { e.printStackTrace(); } } }); //Menu item to show Public Trades showPublicTrades.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { Ticker selectedTicker = tickersTable.getSelectionModel().getSelectedItem(); Parent root; try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_TO_TRADES_LAYOUT), resources); root = (Parent) fxmlLoader.load(); PublicTradesController publicTradesController = fxmlLoader.getController(); publicTradesController.injectPair(selectedTicker.getPair()); Stage stage = new Stage(); stage.setTitle("Public Trades for " + selectedTicker.getPair().replace("_", "/").toUpperCase()); stage.setScene(new Scene(root)); stage.setResizable(false); stage.show(); } catch (IOException e) { e.printStackTrace(); } } }); //Funds Table fundsTableCurrencyColumn.setCellValueFactory(new PropertyValueFactory<Fund, String>("currency")); fundsTableValueColumn.setCellValueFactory(new PropertyValueFactory<Fund, Double>("value")); fundsTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); fundsTable.setItems(fundsData); //Task to load tickers data from server final javafx.concurrent.Service loadTickersService = new javafx.concurrent.Service() { @Override protected Task createTask() { Task<JSONObject> loadTickers = new Task<JSONObject>() { @Override protected JSONObject call() throws Exception { String[] pairsArray = new String[pairs.size()]; pairsArray = pairs.toArray(pairsArray); return App.getPairInfo(pairsArray); } }; loadTickers.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent workerStateEvent) { logField.appendText(workerStateEvent.getSource().getException().getMessage() + "\r\n"); } }); loadTickers.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent workerStateEvent) { JSONObject jsonObject = (JSONObject) workerStateEvent.getSource().getValue(); //ugly hack to store old values //dump old values to tickersData //TODO think about better solution if (tickers.size() != 0) { for (Ticker x : tickers) { tickersData.put(x.getPair(), x); } } tickers.clear(); for (Iterator iterator = jsonObject.keys(); iterator.hasNext();) { String key = (String) iterator.next(); JSONObject data = jsonObject.getJSONObject(key); Ticker ticker = new Ticker(); ticker.setPair(key); ticker.setUpdated(data.optLong("updated")); ticker.setAvg(data.optDouble("avg")); ticker.setBuy(data.optDouble("buy")); ticker.setSell(data.optDouble("sell")); ticker.setHigh(data.optDouble("high")); ticker.setLast(data.optDouble("last")); ticker.setLow(data.optDouble("low")); ticker.setVol(data.optDouble("vol")); ticker.setVolCur(data.optDouble("vol_cur")); tickers.add(ticker); } } }); return loadTickers; } }; //Update tickers every 15 seconds //TODO better solution is required Timeline timeline = new Timeline(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { loadTickersService.restart(); } }), new KeyFrame(Duration.seconds(15))); timeline.setCycleCount(Timeline.INDEFINITE); timeline.playFromStart(); }
From source file:ui.main.MainViewController.java
private void sendMessageSC() { if (currentChat == null) { return;//from w w w .j a v a 2 s . c o m } try { ItemType type = contactsManager.getUserType(currentChat.getParticipant()); if (type.equals(ItemType.none)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Attention!"); alert.setHeaderText("The user is not available for you!"); alert.setContentText( "The user has not accepted the Friend Request." + " The user is not available for you."); alert.showAndWait(); return; } else if (type.equals(ItemType.from)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Attention!"); alert.setHeaderText("An unaccepted user!"); alert.setContentText("You have not accepted the Friend Request." + " You can not send any messages until you accept the friend request."); alert.showAndWait(); return; } else if (type.equals(ItemType.to)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Attention!"); alert.setHeaderText("The user has not accepted!"); alert.setContentText("The user has not accepted the Friend Request." + " You can not send any messages until the user accepts the friend request."); alert.showAndWait(); return; } if (message.getText().isEmpty()) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("IMP"); alert.setHeaderText("Message is empty!"); alert.setContentText("You can not send empty messages."); alert.showAndWait(); return; } try { currentChat.sendMessage(message.getText()); //sends message if (history.isSelected()) { DBSingleChat.saveTextMessage(currentChat.getParticipant(), false, message.getText(), new Timestamp(System.currentTimeMillis())); } paintSendMessage(message.getText().trim(), dtfT.print(DateTime.now())); //paints the sent item message.setText(""); //clears the sent text Task tt = new Task() { @Override protected Object call() throws Exception { Thread.sleep(500); return new Object(); } }; tt.setOnSucceeded(value -> scrollPane.setVvalue(scrollPane.getHmax())); Thread thread1 = new Thread(tt); thread1.start(); } catch (XMPPException ex) { Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex); } } catch (NullPointerException e) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("IMP"); alert.setHeaderText("User is unavailable!"); alert.setContentText("The user is unavailable for you!."); alert.showAndWait(); return; } }
From source file:genrsa.GenRSAController.java
/** * Mtodo usado cuando se pulsa el boton de generarLog de NNC * @param event /*from w w w.j a v a 2 s . c om*/ */ public void generateNNC(ActionEvent event) { if (this.startLogNNC) { //todo se hace antes del thread porque si no nose podria manejar la ventana //para que se decidiera donde se guarda el archivo. FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter("HTML files", "*.html"); FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File(System.getProperty("user.dir"))); fileChooser.getExtensionFilters().add(extensionFilter); fileChooser.setTitle("Seleccionar directorio donde guardar el log"); fileChooser.setInitialFileName("LogNNC genRSA"); File logNNCFile = fileChooser.showSaveDialog(labelPubKey.getScene().getWindow()); Task CAstart = new Task() { @Override protected Object call() throws Exception { startLogNNC = false; progressNNC.setVisible(true); Platform.runLater(() -> { disableOnProgress(true); configureLogStop(true); }); manageKey.saveLogNNC(progressNNC, RSA, logNNCFile); Platform.runLater(() -> { disableOnProgress(false); configureLogStop(false); }); progressNNC.setVisible(false); startLogNNC = true; return null; } }; new Thread(CAstart).start(); } else { this.manageKey.setLogCancelled(); this.startLogNNC = true; } }
From source file:com.jscriptive.moneyfx.ui.chart.ChartFrame.java
/** * This method is invoked when the "by category" button has been toggled * * @param actionEvent//from w w w . j a v a 2s . c o m */ public void byCategoryToggled(ActionEvent actionEvent) { final PieChart pieChart = new PieChart(); pieChart.setTitle("Transaction balance by categories"); pieChart.setLegendSide(LEFT); chartFrame.setCenter(pieChart); ToggleButton toggle = (ToggleButton) actionEvent.getTarget(); if (toggle.isSelected()) { Service<Void> service = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { ValueRange<LocalDate> period = getTransactionOpRange(accountCombo.getValue(), yearCombo.getValue()); if (period.isEmpty()) { return null; } Platform.runLater(() -> pieChart.setTitle(format("%s for transactions from %s until %s", pieChart.getTitle(), period.from().format(DATE_FORMATTER), period.to().format(DATE_FORMATTER)))); categoryRepository.findAll().stream() .sorted((c1, c2) -> c1.getName().compareTo(c2.getName())).forEach(category -> { List<Transaction> found = (accountCombo.getValue() == ALL_ACCOUNTS) ? transactionRepository.findByCategory(category) : transactionRepository.findByAccountAndCategory( accountCombo.getValue(), category); if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) { found = found.stream().filter( trx -> yearCombo.getValue().equals(trx.getDtOp().getYear())) .sorted((t1, t2) -> t1.getDtOp().compareTo(t2.getDtOp())) .collect(toList()); } List<Transaction> transactions = new ArrayList<>(found.size()); transactions.addAll(found); Platform.runLater(() -> { double value = getSum(transactions); String name = format("%s [%s]", category.getName(), CurrencyFormat.getInstance().format(value)); PieChart.Data data = new PieChart.Data(name, value); pieChart.getData().add(data); data.getNode().addEventHandler(MOUSE_CLICKED, event -> handleCategoryChartMouseClickEvent( (accountCombo.getValue() == ALL_ACCOUNTS) ? null : accountCombo.getValue(), category, yearCombo.getValue(), event)); }); }); return null; } }; } }; service.start(); } }
From source file:ui.main.MainViewController.java
private void sendFile() { if (!contactsManager.getAvailabilityforSharing(currentChat.getParticipant())) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Attention!"); alert.setHeaderText("The user is not available!"); alert.setContentText("The file receiving user should be available online to receive the file."); alert.showAndWait();/*from w w w.ja va2 s . c o m*/ return; } ItemType type = contactsManager.getUserType(currentChat.getParticipant()); if (type.equals(ItemType.none)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Attention!"); alert.setHeaderText("This user is not available for you!"); alert.setContentText( "The user has not accepted the Friend Request." + " The user is not available for you."); alert.showAndWait(); return; } else if (type.equals(ItemType.from)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Attention!"); alert.setHeaderText("An unaccepted user!"); alert.setContentText("You have not accepted the Friend Request." + " You can not send any messages until you accept the friend request."); alert.showAndWait(); return; } else if (type.equals(ItemType.to)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Attention!"); alert.setHeaderText("The user has not accepted!"); alert.setContentText("The user has not accepted the Friend Request." + " You can not send any messages until the user accepts the friend request."); alert.showAndWait(); return; } if (!contactsManager.getAvailabilityforSharing(currentChat.getParticipant())) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Attention!"); alert.setHeaderText("The user is not available!"); alert.setContentText("The file receiving user should be available online to receive the file."); alert.showAndWait(); return; } FileChooser fc = new FileChooser(); File file = fc.showOpenDialog(presence.getScene().getWindow()); if (file == null) { return; } Thread t = new Thread(new Runnable() { @Override public void run() { try { fileManager.sendFile(file, currentChat.getParticipant()); if (history.isSelected()) { Timestamp time = new Timestamp(System.currentTimeMillis()); DBSingleChat.saveFileMessage(currentChat.getParticipant(), false, file.getPath(), time); } paintSentFile(currentChat, file.getAbsolutePath(), dtfT.print(DateTime.now())); Task tt = new Task() { @Override protected Object call() throws Exception { Thread.sleep(500); return new Object(); } }; tt.setOnSucceeded(value -> scrollPane.setVvalue(scrollPane.getHmax())); Thread thread1 = new Thread(tt); thread1.start(); } catch (FileNotFoundException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("IMP"); alert.setHeaderText("File is not Found!"); alert.setContentText("File you selected does not exist."); alert.showAndWait(); return; } } }); t.start(); }
From source file:com.QuarkLabs.BTCeClientJavaFX.MainController.java
/** * Gets Active Orders data from server, displays error message at the Log field in case of any Exception *///from w ww. ja va 2 s. c o m @FXML private void showActiveOrders() { Task<JSONObject> task = new Task<JSONObject>() { @Override protected JSONObject call() throws Exception { try { return app.getActiveOrders(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return new JSONObject(); } }; task.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent workerStateEvent) { JSONObject jsonObject = (JSONObject) workerStateEvent.getSource().getValue(); if (jsonObject.optInt("success") == 1) { JSONObject data = jsonObject.getJSONObject("return"); for (Iterator iterator = data.keys(); iterator.hasNext();) { String key = (String) iterator.next(); ActiveOrder activeOrder = new ActiveOrder(); activeOrder.setId(Long.parseLong(key)); activeOrder.setAmount(data.optJSONObject(key).optDouble("amount")); activeOrder.setRate(data.optJSONObject(key).optDouble("rate")); activeOrder.setStatus(data.optJSONObject(key).optInt("status")); activeOrder.setTimestamp(data.optJSONObject(key).optLong("timestamp_created")); activeOrder.setPair(data.optJSONObject(key).optString("pair")); activeOrder.setType(data.optJSONObject(key).optString("type")); activeOrders.add(activeOrder); } activeOrdersTable.setItems(activeOrders); } else { logField.appendText(ERROR_TITLE + jsonObject.optString("error", SOMETHING_WENT_WRONG) + "\r\n"); } } }); task.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent workerStateEvent) { logField.appendText(workerStateEvent.getSource().getException().getMessage() + "\r\n"); } }); Thread thread = new Thread(task); thread.start(); }