List of usage examples for javafx.concurrent Task Task
public Task()
From source file:com.jscriptive.moneyfx.ui.chart.ChartFrame.java
/** * This method is invoked when the daily balance button has been toggled * * @param actionEvent//from w w w .j a v a2s . c o m */ public void dailyBalanceToggled(ActionEvent actionEvent) { LocalDateAxis xAxis = new LocalDateAxis(); NumberAxis yAxis = new NumberAxis(); final LineChart<LocalDate, Number> lineChart = new LineChart<>(xAxis, yAxis); lineChart.setCreateSymbols(false); chartFrame.setCenter(lineChart); ToggleButton toggle = (ToggleButton) actionEvent.getTarget(); if (toggle.isSelected()) { xAxis.setLabel("Day of year"); yAxis.setLabel("Balance in Euro"); lineChart.setTitle("Balance development day by day"); ValueRange<LocalDate> period = getTransactionOpRange(accountCombo.getValue(), yearCombo.getValue()); if (period.isEmpty()) { return; } xAxis.setLowerBound(period.from()); xAxis.setUpperBound(period.to()); Service<Void> service = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { Map<Account, List<Transaction>> transactionMap = getTransactions( accountCombo.getValue(), yearCombo.getValue()); transactionMap.entrySet().forEach(entry -> { Account account = entry.getKey(); List<Transaction> transactionList = entry.getValue(); XYChart.Series<LocalDate, Number> series = new XYChart.Series<>(); series.setName(format("%s [%s]", account.toPresentableString(), account.getFormattedBalance())); // sort transactions by operation value descending transactionList.sort((t1, t2) -> t2.getDtOp().compareTo(t1.getDtOp())); account.calculateStartingBalance(transactionList); series.getData() .add(new XYChart.Data<>(account.getBalanceDate(), account.getBalance())); // sort transactions by operation value ascending transactionList.sort((t1, t2) -> t1.getDtOp().compareTo(t2.getDtOp())); transactionList.forEach(trx -> { account.calculateCurrentBalance(trx); series.getData().add( new XYChart.Data<>(account.getBalanceDate(), account.getBalance())); }); Platform.runLater(() -> lineChart.getData().add(series)); }); return null; } }; } }; service.start(); } }
From source file:sonicScream.controllers.CategoryTabController.java
@FXML private void handleComboBoxChanged(ActionEvent event) { Task task = new Task() { @Override/*from w w w . j av a 2s .c o m*/ protected Object call() throws Exception { try { TreeItem<String> simpleTree = displayMode.get() == CategoryDisplayMode.SIMPLE ? ((Script) CategoryTabComboBox.getValue()).getSimpleTree() : displayMode.get() == CategoryDisplayMode.ADVANCED ? ((Script) CategoryTabComboBox.getValue()).getRootNode() : null; CategoryTabTreeView.setRoot(simpleTree); } catch (Exception ex) { ex.printStackTrace(); } return null; } }; task.run(); }
From source file:herudi.controller.customerController.java
private void displayDiscountCode() { Service<ObservableList<DiscountCode>> service = new Service<ObservableList<DiscountCode>>() { @Override//from w w w.j ava2 s . com protected Task<ObservableList<DiscountCode>> createTask() { return new Task<ObservableList<DiscountCode>>() { @Override protected ObservableList<DiscountCode> call() throws Exception { ObservableList<DiscountCode> listTask = FXCollections.observableArrayList(); if (listTask == null) { listTask = FXCollections.observableArrayList(crud.selectCode()); } else { listTask.clear(); listTask.addAll(crud.selectCode()); } cbDiscount.setItems(listTask); return listTask; } }; } }; service.start(); }
From source file:ExcelFx.FXMLDocumentController.java
@FXML private void Open(ActionEvent event) throws NullPointerException, IOException { System.out.println("-----------------------------------------------------------"); System.out.println("Pressed open Button "); File universityFile = new File("university.json"); File collegeFile = new File("college.json"); System.out.println("University File emty is " + String.valueOf(universityFile.length() == 0)); System.out.println("College File emty is " + String.valueOf(collegeFile.length() == 0)); //File codesFile = new File("codes.json"); if ((universityFile.exists()) && (collegeFile.exists()) /*&& (codesFile.exists())*/) { try {/* w w w. j a v a2s. c o m*/ this.universityJson.jsonRead("university.json"); this.collegeJson.jsonRead("college.json"); //this.codesJson.jsonRead("codes.json"); this.jsonXLSXData.setAll(universityJson, collegeJson/*, codesJson*/); } catch (IOException | ParseException ex) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle(""); alert.setHeaderText(" ? ? "); alert.setContentText(ex.toString()); alert.showAndWait(); Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } } else { try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("FileOpenFXML.fxml")); this.fileOpenParent = (Parent) fxmlLoader.load(); Stage stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); stage.initStyle(StageStyle.DECORATED); stage.setTitle(" "); stage.setScene(new Scene(this.fileOpenParent)); stage.showAndWait(); } catch (Exception e) { System.err.println(e); } this.jsonXLSXData.setAll(universityJson, collegeJson/*, codesJson*/); } FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("InitalData.fxml")); Parent root1 = (Parent) fxmlLoader.load(); Stage stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); stage.initStyle(StageStyle.DECORATED); stage.setTitle(" "); stage.setScene(new Scene(root1)); stage.showAndWait(); setProgressBar(-1.); Task task = new Task<Void>() { @Override protected Void call() throws Exception { initaldata = (JsonWrite) root1.getUserData(); System.out.println("Inital Data empty is " + initaldata.isEmpty()); initaldata.setPage(String.valueOf(Integer.parseInt(initaldata.getPage()) - 1)); Parser parser = new Parser(); list = parser.parseInitalData(initaldata.getPatch(), Integer.parseInt(initaldata.getPage())); //System.out.println(list.size()); Sort sort = new Sort(list, jsonXLSXData, initaldata.getYStart(), initaldata.getYEnd()); HashMap<String, HashMap<String, ArrayList<String>>> hm = sort .professionsGrouping(initaldata.getYStart(), initaldata.getYEnd()); sortProf = sort.addWay(hm); return null; } }; mainProcessing(task); System.out.println("button open finished"); System.out.println("-----------------------------------------------------------"); }
From source file:pe.edu.system.jcmr.controlador.LoguinController.java
@FXML public void btnOnSingIn(ActionEvent event) throws IOException { if (StringUtils.isBlank(txtUsuario.getText())) { lblMensaje.setText(/* w w w .j av a2 s . com*/ getResourceMessage("required.campo.message", new Object[] { txtUsuario.getPromptText() })); return; } if (StringUtils.isBlank(txtPassword.getText())) { lblMensaje.setText( getResourceMessage("required.campo.message", new Object[] { txtPassword.getPromptText() })); return; } if (cboIdioma.getValue().getCodigo().equals("0")) { lblMensaje.setText( getResourceMessage("required.campo.message", new Object[] { cboIdioma.getPromptText() })); return; } Service<TbEmpleado> service = new Service<TbEmpleado>() { @Override protected Task<TbEmpleado> createTask() { return new Task<TbEmpleado>() { @Override protected TbEmpleado call() throws Exception { TbEmpleado employed = employedService.authenticateUser(txtUsuario.getText(), txtPassword.getText()); return employed; } }; } @Override protected void succeeded() { SessionJCMR.getInstance().addContextObject("Usuario", getValue()); SessionJCMR.getInstance().addContextObject("Lenguage", cboIdioma.getValue().getCodigo()); closeWindow(btnSingIn); openWindow(MAIN_FXML); } @Override protected void failed() { lblMensaje.setText(getResourceMessage("errors.password.mismatch")); } }; viewLoader.visibleProperty().bind(service.runningProperty()); rgBack.visibleProperty().bind(service.runningProperty()); service.start(); }
From source file:com.gnadenheimer.mg3.controller.admin.AdminConfigController.java
@FXML private void cmdUpdateSET(ActionEvent event) { Task taskUpdateSET = new Task<Void>() { @Override/*from w ww . jav a 2s.c om*/ public Void call() { try { EntityManager entityManager = Utils.getInstance().getEntityManagerFactory() .createEntityManager(); entityManager.getTransaction().begin(); String temp = ""; Integer count = 0; entityManager.createQuery("delete from TblContribuyentes t").executeUpdate(); for (Integer i = 0; i <= 9; i++) { URL url = new URL( "http://www.set.gov.py/rest/contents/download/collaboration/sites/PARAGUAY-SET/documents/informes-periodicos/ruc/ruc" + String.valueOf(i) + ".zip"); ZipInputStream zipStream = new ZipInputStream(url.openStream(), StandardCharsets.UTF_8); zipStream.getNextEntry(); Scanner sc = new Scanner(zipStream, "UTF-8"); while (sc.hasNextLine()) { String[] ruc = sc.nextLine().split("\\|"); temp = ruc[0] + " - " + ruc[1] + " - " + ruc[2]; if (ruc[0].length() > 0 && ruc[1].length() > 0 && ruc[2].length() == 1) { TblContribuyentes c = new TblContribuyentes(); c.setRucSinDv(ruc[0]); c.setRazonSocial(StringEscapeUtils.escapeSql(ruc[1])); c.setDv(ruc[2]); entityManager.persist(c); updateMessage("Descargando listado de RUC con terminacion " + String.valueOf(i) + " - Cantidad de contribuyentes procesada: " + String.format("%,d", count) + " de aprox. 850.000."); count++; } else { updateMessage(temp); } } entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); } updateMessage("Lista de RUC actualizada..."); return null; } catch (Exception ex) { App.showException(this.getClass().getName(), ex.getMessage(), ex); } return null; } }; lblUpdateSET.textProperty().bind(taskUpdateSET.messageProperty()); new Thread(taskUpdateSET).start(); }
From source file:net.rptools.tokentool.controller.ManageOverlays_Controller.java
private void loadImages(File dir) { // Clear Details panel clearDetails();/*from ww w. j a va2 s.c om*/ currentDirectory = dir; File[] files = dir.listFiles(ImageUtil.SUPPORTED_FILENAME_FILTER); Task<Void> task = new Task<Void>() { @Override public Void call() { for (File file : files) { Path filePath = file.toPath(); if (loadOverlaysThread.isInterrupted()) { Platform.runLater(() -> overlayViewFlowPane.getChildren().clear()); break; } try { ToggleButton overlayButton = new ToggleButton(); ImageView imageViewNode = ImageUtil.getOverlayThumb(new ImageView(), filePath); overlayButton.getStyleClass().add("overlay-toggle-button"); overlayButton.setGraphic(imageViewNode); overlayButton.setUserData(file); overlayButton.setToggleGroup(overlayToggleGroup); overlayButton.addEventHandler(ActionEvent.ACTION, event -> { // No modifier keys used so add toggle group back to all buttons resetToggleGroup(); // Also set button to selected due to resetting toggle groups & no unselecting needed, makes for better interface IMO overlayButton.setSelected(true); // Update the Details panel with the last selected overlay File overlayFile = (File) overlayButton.getUserData(); updateDetails(overlayFile, (ImageView) overlayButton.getGraphic(), overlayButton.isSelected()); // Consume the event, no more logic needed event.consume(); }); overlayButton.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { // Allow multiple selections if shortcutKey+left_mouse is pressed if (event.getButton().equals(MouseButton.PRIMARY) && event.isShortcutDown()) { // Update the Details panel with the last selected overlay File overlayFile = (File) overlayButton.getUserData(); updateDetails(overlayFile, (ImageView) overlayButton.getGraphic(), true); // Remove the toggle group to allow multiple toggle button selection overlayButton.setToggleGroup(null); // Select the button overlayButton.setSelected(true); // Consume the event, no more logic needed event.consume(); } } }); Platform.runLater(() -> overlayViewFlowPane.getChildren().add(overlayButton)); } catch (IOException e) { log.error("Loading image: " + filePath.getFileName(), e); } } return null; } }; loadOverlaysThread.interrupt(); executorService.execute(task); }
From source file:com.respam.comniq.Controller.java
public Task OMDBworker() { return new Task() { @Override/*from www . j a v a 2 s .c o m*/ protected Object call() throws Exception { OMDBParser op = new OMDBParser(); JSONParser parser = new JSONParser(); String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output"; try { Object obj = parser.parse(new FileReader(path + File.separator + "LocalList.json")); JSONArray parsedArr = (JSONArray) obj; // Loop JSON Array for (int i = 0; i < parsedArr.size(); i++) { JSONObject parsedObj = (JSONObject) parsedArr.get(i); String movieName = (String) parsedObj.get("movie"); String movieYear = (String) parsedObj.get("year"); System.out.println(movieName + "-" + movieYear); op.requestOMDB(movieName, movieYear); updateProgress(i, parsedArr.size() - 1); } op.movieInfoWriter(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return true; } }; }
From source file:com.bekwam.resignator.JarsignerConfigController.java
private void loadAliases() { if (StringUtils.isNotEmpty(tfKeystore.getText()) && StringUtils.isNotEmpty(pfStorepass.getText())) { if (logger.isDebugEnabled()) { logger.debug("[LOAD ALIASES] there are values for the keytool command"); }/*from ww w . j ava 2 s .c o m*/ hboxAliasProgress.setVisible(true); cbAlias.valueProperty().unbindBidirectional(activeProfile.jarsignerConfigAliasProperty()); cbAlias.getItems().clear(); final String ks = tfKeystore.getText(); final String sp = pfStorepass.getText(); Task<Void> t = new Task<Void>() { public Void call() { try { updateMessage("Loading..."); updateProgress(0.1d, 1.0d); final List<String> aliases = keytoolCommand .findAliases(activeConfiguration.getKeytoolCommand().toString(), ks, sp); updateMessage("Updating..."); updateProgress(0.8d, 1.0d); Platform.runLater(() -> { if (CollectionUtils.isNotEmpty(aliases)) { cbAlias.getItems().addAll(aliases); cbAlias.valueProperty() .bindBidirectional(activeProfile.jarsignerConfigAliasProperty()); } cbAlias.setDisable(false); // might be an empty list for empty keystore cbAlias.requestFocus(); // leave the PasswordField hboxAliasProgress.setVisible(false); }); } catch (CommandExecutionException exc) { if (logger.isWarnEnabled()) { logger.warn("error getting aliases", exc); } Platform.runLater(() -> { cbAlias.setDisable(true); hboxAliasProgress.setVisible(false); }); } finally { updateMessage(""); updateProgress(0.0d, 1.0d); } return null; } }; lblAliasProgress.textProperty().bind(t.messageProperty()); pbAlias.progressProperty().bind(t.progressProperty()); new Thread(t).start(); } else { cbAlias.getItems().clear(); cbAlias.setDisable(true); } }
From source file:herudi.controller.productController.java
private void displayManufacturer() { Service<ObservableList<Manufacturer>> service = new Service<ObservableList<Manufacturer>>() { @Override/* w w w . ja v a 2 s. c om*/ protected Task<ObservableList<Manufacturer>> createTask() { return new Task<ObservableList<Manufacturer>>() { @Override protected ObservableList<Manufacturer> call() throws Exception { ObservableList<Manufacturer> listTask = FXCollections.observableArrayList(); if (listTask == null) { listTask = FXCollections.observableArrayList(crud.selectManufacturerID()); } else { listTask.clear(); listTask.addAll(crud.selectManufacturerID()); } cbManufacturer.setItems(listTask); return listTask; } }; } }; service.start(); }