binding progress bar with a method, javafx - javafx

I have a method which performs some task(reading, writing files and other tasks also) for almost 3 minutes.
I want to bind progress bar in javafx which can run with progress of the method.
This is my method
System.out.println("Going to load contract/security:"+new Date());
Map<Integer,FeedRefData> map = loadContractAndSecurityFromFile(loadFO);
addIndicesRefData(map);
BufferedWriter writer = createFile();
for (FeedRefData feedRefData : map.values()) {
try {
updateInstrumentAlias(map, feedRefData);
String refDataString = feedRefData.toString();
writer.write(refDataString, 0, refDataString.length());
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
log.info("Unable to write Quote Object to : " );
}
}
System.out.println("Ref Data File Generated:"+new Date());

For bind your method with progressbar you should do these steps :
Create a task which contains your method.
Create a thread which run this task.
Bind your progress property with your task property.
I made this simple example ,just change my code with your method code :
public class Bind extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
ProgressBar pb = new ProgressBar();
pb.setProgress(1.0);
Button button = new Button("start");
button.setOnAction((ActionEvent event) -> {
/*Create a task which contain method code*/
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
File file = new File("C:\\Users\\Electron\\Desktop\\387303_254196324635587_907962025_n.jpg");
ByteArrayOutputStream bos = null;
try {
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
bos = new ByteArrayOutputStream();
for (int len; (len = fis.read(buffer)) != -1;) {
bos.write(buffer, 0, len);
updateProgress(len, file.length());
/* I sleeped operation because reading operation is quiqly*/
Thread.sleep(1000);
}
System.out.println("Reading is finished");
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
} catch (IOException e2) {
System.err.println(e2.getMessage());
}
return null;
}
};
Thread thread = new Thread(task);
thread.start();
/*bind the progress with task*/
pb.progressProperty()
.bind(task.progressProperty());
});
HBox box = new HBox(pb, button);
Stage stage = new Stage();
StackPane root = new StackPane();
root.getChildren().add(box);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}
Operation started :
Operation finished :
PS: I used Thread.sleep(1000) because my file is so small.You can remove it if your progress time is long.

Related

Working with application in Java using maps

I have trouble with my Java application. I'm writing a program that connects to public transport API and perform some operations, which includes showing map of Warsaw with bus stops. I want to add an EventHandler function that allows to tap on a bus stop on the map, which will result in showing a box with some informations about this bus stop. How can I do such a thing?
My application so far:
Main.java:
package gui;
import api.Api;
import com.gluonhq.charm.down.ServiceFactory;
import com.gluonhq.charm.down.Services;
import com.gluonhq.charm.down.plugins.StorageService;
import com.gluonhq.maps.MapPoint;
import com.gluonhq.maps.MapView;
import com.gluonhq.maps.demo.PoiLayer;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.io.File;
import java.util.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Main extends Application{
private ContentType currentContent = ContentType.SCHEDULE;
private HashMap<ContentType, Pane> contentPaneMap;
private HBox buttonBox;
private Stage stage;
private Theme theme;
private final int height = 500;
private final int width = 800;
private final ToggleGroup menuButtonToggle = new ToggleGroup();
private String selectedStopId;
#Override
public void start(Stage primaryStage) {
this.stage = primaryStage;
theme = Theme.DARK;
buttonBox = new HBox();
buttonBox.getChildren().addAll(getMenuButtons());
initContentPanes();
getContentPaneAndResetStage();
primaryStage.show();
}
private void getContentPaneAndResetStage(){
Pane contentPane = contentPaneMap.get(currentContent);
VBox rootPane = new VBox();
rootPane.getChildren().addAll(buttonBox, contentPane);
Scene scene = new Scene(rootPane, width, height);
scene.getStylesheets().add(theme.cssFile);
stage.setScene(scene);
}
private List<ToggleButton> getMenuButtons(){
List<ToggleButton> buttonList = new ArrayList<>();
for(ContentType contentType:ContentType.values()){
ToggleButton button = new ToggleButton(contentType.buttonText);
button.setPrefWidth((double) width/4);
button.setOnAction(e -> {
Main.this.currentContent = contentType;
getContentPaneAndResetStage();
});
buttonList.add(button);
button.setToggleGroup(Main.this.menuButtonToggle);
}
return buttonList;
}
private void initContentPanes(){
contentPaneMap = new HashMap<>();
Api.saveLocalisationToCache();
contentPaneMap.put(ContentType.MAP, getMapPane());
contentPaneMap.put(ContentType.SCHEDULE, getSchedulePane());
contentPaneMap.put(ContentType.ROUTE, getRoutePane());
contentPaneMap.put(ContentType.SETTINGS, getSettingsPane());
}
private Pane getSchedulePane(){
VBox schedulePane = new VBox();
Label stopNameLabel = new Label("Nazwa przystanku: ");
stopNameLabel.setPadding(new Insets(5));
TextField stopName = new TextField();
stopName.setOnAction(e -> {
List<String> stopId = Api.getId(stopName.getText());
selectedStopId = null;
schedulePane.getChildren().remove(1);
schedulePane.getChildren().add(getContentForSchedulePane(stopId, stopName.getText()));
});
schedulePane.getChildren().add(new HBox(stopNameLabel, stopName));
if (selectedStopId == null) schedulePane.getChildren().add(new Pane(new Label("Nie znaleziono przystanku")));
else schedulePane.getChildren().add(new Label(selectedStopId));
return schedulePane;
}
private Pane getContentForSchedulePane(List<String> stopId, String stopName){
if (stopId.size() == 0) return new Pane(new Label("Nie znaleziono przystanku"));
if (stopId.size() == 1) {
String stop1id = stopId.get(0);
Label stopNameLabel = new Label("Przystanek " + stopName.toUpperCase() + " (id " + stop1id + ")");
stopNameLabel.setPadding(new Insets(5));
VBox newContentPane = new VBox(stopNameLabel);
ChoiceBox<String> busStopNr = new ChoiceBox<>(
FXCollections.observableArrayList(List.of(new String[]{"01", "02"})));
busStopNr.setValue("01");
ChoiceBox<String> lineChoice = new ChoiceBox<>(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue())));
Label times = new Label();
lineChoice.setOnAction(
e -> times.setText(Api.getTimes(stop1id, busStopNr.getValue(), lineChoice.getValue()).toString()));
busStopNr.setOnAction(
e -> lineChoice.setItems(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue()))));
newContentPane.getChildren().addAll(
new HBox(new Label("Nr słupka: "), busStopNr),
new HBox(new Label("Nr linii: "), lineChoice),
times);
return newContentPane;
}
GridPane newButtonPane = new GridPane();
int i = 1; int j = 0;
for (String id:stopId) {
Button b = new Button(id);
b.setOnAction(event -> {
selectedStopId = b.getText();
contentPaneMap.get(ContentType.SCHEDULE).getChildren().remove(1);
contentPaneMap.get(ContentType.SCHEDULE).getChildren()
.add(getContentForSchedulePane(Collections.singletonList(b.getText()), stopName));
});
((GridPane) newButtonPane).add(b, i, j);
i = (i+1)%4+1; j = i==1?j+1:j;
}
return newButtonPane;
}
private Pane getRoutePane(){return new VBox(new Circle(20, Color.BLUE));}
private Pane getMapPane(){
MapView mapView = new MapView();
PoiLayer poiLayer = new PoiLayer();
List<Map<String, String>> pointList = Api.getLocalization();
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
poiLayer.addPoint(point, new Circle(3, Color.RED));
}
mapView.setCenter(new MapPoint(52.230926, 21.006701));
mapView.setZoom(13);
mapView.addLayer(poiLayer);
return new StackPane(mapView);
}
public void getInfo(){
}
private Pane getSettingsPane(){
GridPane settingsPane = new GridPane();
ChoiceBox<Theme> themeChoiceBox = new ChoiceBox<>(FXCollections.observableArrayList(Theme.values()));
themeChoiceBox.setOnAction(e -> {
Main.this.theme = themeChoiceBox.getValue();
getContentPaneAndResetStage();
});
Label themeLabel = new Label("Motyw: ");
themeLabel.setPadding(new Insets(5));
settingsPane.add(themeLabel, 1, 1);
settingsPane.add(themeChoiceBox, 2, 1);
settingsPane.setHgap(10);
settingsPane.setVgap(10);
settingsPane.setGridLinesVisible(false);
return settingsPane;
}
#Override
public void init() {
System.setProperty("javafx.platform", "Desktop");
System.setProperty("http.agent", "Gluon Mobile/1.0.1");
StorageService storageService = new StorageService() {
#Override
public Optional<File> getPrivateStorage() {
return Optional.of(new File(System.getProperty("user.home")));
}
#Override
public Optional<File> getPublicStorage(String s) {
return getPrivateStorage();
}
#Override
public boolean isExternalStorageWritable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canWrite();
}
#Override
public boolean isExternalStorageReadable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canRead();
}
};
ServiceFactory<StorageService> storageServiceServiceFactory = new ServiceFactory<>() {
#Override
public Class<StorageService> getServiceType() {
return StorageService.class;
}
#Override
public Optional<StorageService> getInstance() {
return Optional.of(storageService);
}
};
Services.registerServiceFactory(storageServiceServiceFactory);
}
}
api.java:
package api;
import javafx.application.Platform;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Api {
private static final String baseUrl = "https://api.um.warszawa.pl/api/action/";
private static final String apikey = "95904037-5fdc-48d5-bd7f-c9f8d0b28947";
private static final String pathToLocalisationCache = "./.cache/stop-localisation.json";
private static HttpURLConnection getConnection(String urlString){
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
assert url != null;
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
//Współrzędne przystanków
public static List<Map<String,String>> getLocalization() {
File cacheFile = new File(pathToLocalisationCache);
String data;
if(!cacheFile.exists()){
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
data = Api.readData(connection);
} else{
data = readLocalisationFromCache();
}
List<Map<String,String>> list = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
Map<String, String> map = new HashMap<>();
for(int i = 0; i < arr1.length();i++){
String value = arr1.getJSONObject(i).getString("value");
String key = arr1.getJSONObject(i).getString("key");
map.put(key, value);
}
list.add(map);
}
return list;
}
public static void saveLocalisationToCache(){
File file = new File(pathToLocalisationCache);
if (file.exists()) return;
try{
boolean fileCreated = true;
if (!file.getParentFile().exists()) fileCreated = file.getParentFile().mkdir();
if (!fileCreated) throw new IOException("Unable to create cache directory");
fileCreated = file.createNewFile();
if (!fileCreated) throw new IOException("Unable to create file");
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = setParameters(getConnection(url));
InputStreamReader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()), StandardCharsets.UTF_8.newDecoder());
OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8.newEncoder());
in.transferTo(out);
in.close(); out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String readLocalisationFromCache(){
try{
BufferedReader reader = new BufferedReader(new FileReader(pathToLocalisationCache));
StringBuilder dataSB = new StringBuilder();
reader.lines().forEach(dataSB::append);
reader.close();
return dataSB.toString();
} catch (IOException e){e.printStackTrace();}
return null;
}
//id przystanku po nazwie
public static List<String> getId(String n) {
StringBuilder name = new StringBuilder();
try {
String[] testStrings = {n};
for (String s : testStrings) {
String encodedString = URLEncoder.encode(s, StandardCharsets.UTF_8);
name.append(encodedString);
}
} catch(Exception e){e.printStackTrace();}
String url = baseUrl+"dbtimetable_get?id=b27f4c17-5c50-4a5b-89dd-236b282bc499&name="+name+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
// Zwraca liste linii dla konkretnego przystanku i nr slupka
public static List<String> getLines(String idPrzystanku, String nrSlupka) {
String url = baseUrl+"dbtimetable_get?id=88cd555f-6f31-43ca-9de4-66c479ad5942&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
//Zwraca listę czas dla danego przystanku i linii
public static List<String> getTimes(String idPrzystanku, String nrSlupka, String line) {
String url = baseUrl+"dbtimetable_get?id=e923fa0e-d96c-43f9-ae6e-60518c9f3238&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&line="+line+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
List<String> times = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
JSONObject obj2 = arr1.getJSONObject(5);
times.add(obj2.getString("value"));
}
return times;
}
//Odczytuje dane
public static String readData(HttpURLConnection connection) {
InputStream inStream;
try {
inStream = new BufferedInputStream(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
Scanner in = new Scanner(inStream, StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNext()) {
sb.append(in.next());
}
return sb.toString();
}
//Ustala parametry połączenia
public static HttpURLConnection setParameters(HttpURLConnection
connection) {
try {
connection.setRequestMethod("GET");
connection.setDoInput(true);
} catch (ProtocolException e) {
e.printStackTrace();
}
connection.setRequestProperty("Authorization", "Token " + apikey);
try {
if (connection.getResponseCode() != 200) {
System.out.println("Response code: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
Platform.exit(); // ze względu na javafx
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
I have no idea how to do it and I will be very grateful if someone will help me.
Based on my work experience on map libraries with JavaFX, I can share an approach you can take here. You can simply add a Mouse click event handler on the MapView and in that event you can catch the coordinates/Point where the user clicks on the screen. Then you can compare that point clicked by the user with one of the location Map points you want your user to click and see if it matches (by checking a distance between the user click position and the map coordinate of the bus stop). I have applied this approach in a different map library but similar can be applied here with some tweaks and adjustments.
List<Map<String, String>> pointList = Api.getLocalization();
mapView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
Point2D clickedMapCoordinates = mapView.screenToLocal(new Point2D(mouseEvent.getX(), mouseEvent.getY()));
for (Map<String, String> stop: pointList){
MapPoint stopPoint = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
Point2D mapStopPoint = new Point2D(stopPoint.getLongitude(), stopPoint.getLatitude());
// if user clicked on map near the position(lat,lng) of a stop
// then trigger the logic, you can change the distance threshold value according to your need
if(mapStopPoint.distance(clickedMapCoordinates) < 0.0001)
{
// perform your logic here about the stop point point...
}
}
}
});
Another approach which I suppose you can take is put a click event handler on the Circle object for the bus stop point and then check if the user's clicked circle matches the coordinates of a bus stop point.
Circle circle = new Circle(3, Color.RED);
circle.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getSource() instanceof Circle)
{
Circle clickedCircle = (Circle) mouseEvent.getSource();
Point2D clickedPoint = mapView.screenToLocal(clickedCircle.getCenterX(), clickedCircle.getCenterY())
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
if(clickedPoint.getX() == point.getLongitude() && clickedPoint.getY() == point.getLatitude())
{
// this is the clicked map point (bus stop point)
// perform your logic here
}
}
}
}
});
If the second approach doesn't work, try debugging and checking the clicked point and bus stop point coordinates values and adjust them. Hope this helps you in some way.

ScalaFX Dialog onShown runs BEFORE the dialog is shown [duplicate]

Button button = new Button("Show Text");
button.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
Platform.runLater(new Runnable(){
#Override
public void run() {
field.setText("START");
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Platform.runLater(new Runnable(){
#Override
public void run() {
field.setText("END");
}
});
}
});
After running the code above, field.setText("START") is not executed, I mean textfield did not set its text to "START", WHY? How to resolve this?
Keep in mind that the button's onAction is called on the JavaFX thread, therefore you are effectively halting your UI thread for 5 seconds. When the UI thread is un-frozen at the end of these five seconds both changes are applied successively, so you end up only seeing the second.
You can fix this by running all code above in a new thread:
Button button = new Button();
button.setOnAction(event -> {
Thread t = new Thread(() -> {
Platform.runLater(() -> field.setText("START"));
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Platform.runLater(() -> field.setText("END"));
});
t.start();
});

JavaFX - creating a new window on button clicked(using Scene Builder) [duplicate]

Looking at this code they show a way to display a new window after a login. When username and password are correct it opens new dialog. I want a button click to open new dialog, without checking for username and password.
If you just want a button to open up a new window, then something like this works:
btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Parent root;
try {
root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
Stage stage = new Stage();
stage.setTitle("My New Stage Title");
stage.setScene(new Scene(root, 450, 450));
stage.show();
// Hide this current window (if this is what you want)
((Node)(event.getSource())).getScene().getWindow().hide();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I use the following method in my JavaFX applications.
newWindowButton.setOnMouseClicked((event) -> {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
});
The code below worked for me I used part of the code above inside the button class.
public Button signupB;
public void handleButtonClick (){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
}

Access textarea in one controller from another controller JavaFX

I have two controllers FXMLDocumentController and FXMLOpenedCodeController. I am reading the contents of a .txt file from FXMLDocumentController and I want that text to be placed in a textarea in the FXMLOpenedCodeController. The code is running and reading well from the FXMLDocumentController but when the window from FXMLOpenedCodeController is opened, the read contents from .txt contents is not visible in the textarea. My system.out.println shows that String mine has the contents but it is not showing in the textarea in FXMLOpenedCodeController. Please help anyone. Thank you.
FXMLDocumentController code
public class FXMLDocumentController implements Initializable {
#FXML
private MenuItem open;
#FXML
private MenuItem about;
#Override
public void initialize(URL url, ResourceBundle rb) {
open.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle (ActionEvent event){
try {
showSingleFileChooser();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
private void showSingleFileChooser() throws IOException {
//Stage s = new Stage();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("ZEBRA file open...");
FileChooser.ExtensionFilter exfil = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(exfil);
File selectedFile = fileChooser.showOpenDialog(stage);
if(selectedFile != null){
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("FXMLOpenedCode.fxml"));
AnchorPane frame = (AnchorPane) fxmlLoader.load();
FXMLOpenedCodeController c = fxmlLoader.getController();
//c.codeExecute = codeExecute;
c.codeExecute.appendText(readFile(selectedFile));
String mine;
mine = readFile(selectedFile);
//c.codeExecute.appendText(mine);
System.out.println(mine);
Parent root = FXMLLoader.load(getClass().getResource("FXMLOpenedCode.fxml"));
Scene scene = new Scene(root);
stage4.initModality(Modality.APPLICATION_MODAL);
stage4.setTitle("Compile Code");
stage4.setScene(scene);
stage4.show();
}
}
private void newWindow() throws IOException{
Parent root = FXMLLoader.load(getClass().getResource("FXMLNew.fxml"));
Scene scene = new Scene(root);
stage3.initModality(Modality.APPLICATION_MODAL);
stage3.setTitle("Enter code to run here");
stage3.setScene(scene);
stage3.show();
}
private String readFile(File selectedFile) throws FileNotFoundException, IOException {
StringBuilder content = new StringBuilder();
BufferedReader buffRead = null;
buffRead = new BufferedReader(new FileReader(selectedFile));
String text;
while((text = buffRead.readLine())!=null){
content.append(text);
}
return content.toString();
}
}
and in the FXMLOpenedCodeController there is a public TextArea codeExecute; I removed the #FXML and private so that the code works.
You are loading FXMLOpenedCode.fxml twice. You put the text in the text area you get from loading it the first time, but then you display the UI you get from loading it the second time. So, obviously, you don't see the text as it is set to the wrong text area.
Just load the FXML file once:
if(selectedFile != null){
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("FXMLOpenedCode.fxml"));
AnchorPane frame = (AnchorPane) fxmlLoader.load();
FXMLOpenedCodeController c = fxmlLoader.getController();
//c.codeExecute = codeExecute;
String mine;
mine = readFile(selectedFile);
c.codeExecute.appendText(mine);
System.out.println(mine);
Scene scene = new Scene(frame);
stage4.initModality(Modality.APPLICATION_MODAL);
stage4.setTitle("Compile Code");
stage4.setScene(scene);
stage4.show();
}

refresh label during a foreach loop

I'm asking for your help.
I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Here is my problem. I did a foreach loop of a list for every .mp3 found but I'd like to increment a label which inform the progression of the list.
Here is my code
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
this.labelUpdate.setText(this.current++ + " of " + " size");
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
}
Actually, when the loop progress my window interface is completely freeze.
And only when the loop is finished, the label updated.
Someone can explain why ?
I already thank you for your answers.
EDIT :
Here is my fully code
public class LaunchOption extends Pane {
private final HBox launchAndSend = new HBox();
private final HBox browseAndField = new HBox();
private final HBox jsonAndAdvance = new HBox();
private ArrayList<DataSong> lsWithData = new ArrayList<>();
private String sendJson;
private File selectedDirectory;
private User user;
private int currentData;
private final ProgressIndicator pi = new ProgressIndicator(0);
private final VBox containerElement = new VBox();
private final TextArea displayJson = new TextArea();
private final TextField pathDir = new TextField();
private final TextField nbrOfData = new TextField();
private final Button btnScan = new Button();
private final Button btnSend = new Button();
private final Button btnCheckJson = new Button();
private final Button btnDirectoryBrowser = new Button();
private final Label nbMp3 = new Label();
public Label listAdvance = new Label();
private final Stage home;
public LaunchOption(Stage home){
this.home = home;
configureBtnCheckJson();
configureBtnScan();
configureBtnSend();
configureLabelMp3();
configureBtnDirectoryBrowser();
configureTextAreaDisplayJson();
configureTextFieldPathDir();
configureTextFieldNbDataMp3();
configureHBoxlaunchSend();
configureHBoxBrowseAndField();
configureHBoxJsonAndAdvance();
configureContainer();
this.getChildren().addAll(containerElement,launchAndSend);
}
private void configureLabelMp3()
{
nbMp3.setText("MP3");
}
private void configureBtnScan(){
btnScan.setText("Scan");
btnScan.setOnAction(event->{
ArrayList<String> Mp3FileData;
Mp3FileData = mapFilesMp3(selectedDirectory.getAbsolutePath());
System.out.println("ListSize = " + Mp3FileData.size());
nbrOfData.setText(String.valueOf(Mp3FileData.size()));
try {
lsWithData = checkMp3File(Mp3FileData, selectedDirectory.getAbsolutePath());
} catch (UnsupportedTagException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
}
pi.setProgress(1);
});
}
private void configureBtnDirectoryBrowser(){
btnDirectoryBrowser.setText("Browse ...");
btnDirectoryBrowser.getStyleClass().add("round-red");
btnDirectoryBrowser.setOnAction(event-> {
DirectoryChooser dc = new DirectoryChooser();
selectedDirectory = dc.showDialog(home);
pi.setProgress(0.35);
if(selectedDirectory == null)
{
pathDir.setText("No directory selected");
}
else
{
pathDir.setText(selectedDirectory.getAbsolutePath());
String Text = pathDir.getText();
System.out.println(Text.toString());
}
});
}
private static String regexMp3()
{
return "^.*\\.(mp3)$";
}
private ArrayList mapFilesMp3(String sDir){
ArrayList<String> ls = new ArrayList<>();
printFnames(sDir,ls);
return ls;
}
private static void printFnames(String sDir, ArrayList<String> ls)
{
File[] faFiles = new File(sDir).listFiles();
for(File file : faFiles)
{
if(file.getName().matches(regexMp3()))
{
// System.out.println(file.getAbsolutePath());
ls.add(file.getAbsolutePath());
}
if(file.isDirectory())
{
printFnames(file.getAbsolutePath(), ls);
}
}
}
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
System.out.println(this.currentData++);
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3.getId3v2Tag();
if(!(id3v2Tag.getArtist() == null))
{
ds.setArtist(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getAlbum() == null))
{
ds.setAlbum((id3v2Tag.getAlbum()));
}
if(!(id3v2Tag.getTitle() == null))
{
ds.setTitle(id3v2Tag.getTitle());
}
if(!(id3v2Tag.getTrack() == null))
{
ds.setTrackOnAlbum(id3v2Tag.getTrack());
}
if(!(id3v2Tag.getYear() == null) && !(id3v2Tag.getYear().isEmpty()))
{
ds.setYearReleased(id3v2Tag.getYear());
}
if(!(id3v2Tag.getGenreDescription() == null))
{
ds.setGenre(id3v2Tag.getGenreDescription());
}
if(!(id3v2Tag.getComposer() == null))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(id3v2Tag.getPublisher() == null))
{
ds.setPublisher(id3v2Tag.getPublisher());
}
if(!(id3v2Tag.getOriginalArtist() == null))
{
ds.setOriginArtist(id3v2Tag.getOriginalArtist());
}
if(!(id3v2Tag.getAlbumArtist() == null))
{
ds.setAlbumArtString(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getCopyright() == null))
{
ds.setCopyright(id3v2Tag.getCopyright());
}
if(!(id3v2Tag.getUrl() == null))
{
ds.setUrl(id3v2Tag.getUrl());
}
}
}
lsds.add(ds);
}
return lsds;
}
I presume that what I should do is to make my checkMp3File method into a Task method which will do a background thread ?
There is not enough code to be sure but I think you are probably calling your method on the JavaFX application thread which then blocks your UI.
You should read the documentation about concurrency in JavaFX.
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm

Resources