JavaFX log4j in a textarea with a different thread - javafx

I'm trying to redirect log4j output to a textarea but this one get filled at the end of the action since I'm using Platform.runLater
Is there any way I can do it with a different thread ?
AppFX.java
public class AppFX extends Application {
public static void main(String[] args) {
ConfHandler.initConf();
launch(args);
}
#Override
public void start(Stage primaryStage)throws IOException {
primaryStage.getIcons().add(new Image("file:src/main/resources/images/frameIcon.png"));
FXMLLoader loader = new FXMLLoader();
String currentPath = System.getProperty("user.dir");
loader.setLocation(new URL("file:\\"+currentPath+"\\src\\main\\resources\\scenes\\TestsFrame.fxml"));
Parent content = loader.load();
primaryStage.setTitle("IGED Tests");
Scene scene = new Scene(content);
primaryStage.setScene(scene);
primaryStage.show();
TextAreaAppender.setTextArea(((EaaSCleanerController)loader.getController()).getLogTextArea());
}}
TextAreaAppender.java
public class TextAreaAppender extends WriterAppender {
private static volatile TextArea textArea = null;
public static void setTextArea(final TextArea textArea) {
TextAreaAppender.textArea = textArea;
}
#Override
public void append(final LoggingEvent loggingEvent) {
final String message = this.layout.format(loggingEvent);
try {
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
if (textArea != null) {
if (textArea.getText().length() == 0) {
textArea.setText(message);
} else {
textArea.selectEnd();
textArea.insertText(textArea.getText().length(), message);
}
}
} catch (final Throwable t) {
System.out.println("Unable to append log to textarea:" + t.getMessage());
}
}
});
} catch (final IllegalStateException e) {
}
}}
log4j.properties
# Append the logs to the GUI
log4j.appender.gui=com.bp.nest.testauto.gui.TextAreaAppender
log4j.appender.gui.layout=org.apache.log4j.PatternLayout
log4j.appender.gui.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n

You should put your actions on a separate thread. Then the logging can happen in parallel to your actions. You should never block the GUI-thread.

Related

JavaFX - How to switch to another tab with mouse click event [duplicate]

So I'm trying to load and save Images into an imageView where the location of the image is chosen through a file browser. I've been working on this for several days now and I'm gonna have a stroke if I can't get it fixed. I've tried everything I can think of. Thank you in advance for helping.
UPDATED:
Here is my main class:
public class Main extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
public Main(){}
#Override
public void start(Stage primaryStage) throws Exception{
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Help Please");
initRootLayout();
showScreen();
}
public void initRootLayout(){
try{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
RootLayout controller = loader.getController();
controller.setMain(this);
primaryStage.show();
}catch(Exception e ){e.printStackTrace();}
}
public void showScreen(){
try{FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/sample.fxml"));
BorderPane sample = (BorderPane)loader.load();
rootLayout.setCenter(sample);
Controller controller = loader.getController();
controller.setMain(this);
}catch (Exception e){e.printStackTrace();}
}
public Stage getPrimaryStage(){return primaryStage;}
public static void main(String[] args) {
launch(args);
}
}
Here is the rootLayout:
public class RootLayout {
private Main main;
private Controller controller = new Controller();
public void setMain(Main main){this.main = main;}
#FXML
private void handleOpen(){
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter(
"PNG files (*.png)","*png");
fileChooser.getExtensionFilters().add(extensionFilter);
File file = fileChooser.showOpenDialog(main.getPrimaryStage());
if(file!= null){
controller.updateImage(file.toURI().toString());
}
}
}
And here is the controller:
public class Controller implements Initializable {
#FXML
ImageView imageView = new ImageView();
String imageURL;
Main main = new Main();
public void setMain(Main main){
this.main = main;
}
public void updateImage(String url){
if(url.length()>=1){
Image image = new Image(url);
imageView.setImage(image);
System.out.println(url);
}
else{
System.out.println(url);
System.out.println("image invalid");
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
}
Two things:
Never assign a field whose value is to be injected by an FXMLLoader (e.g. #FXML fields). Doing so is a waste of resources at best and introduces subtle bugs at worst. For instance, if you were to leave the imageView field uninitialized you'd be getting a NullPointerException which would indicate a problem with your setup. Since you do initialize the field, however, you don't get any errors and there's a false impression of the code working.
In your RootLayout controller class, you have:
private Controller controller = new Controller();
That instance of Controller you just created is not linked to any FXML file. And since you initialize the imageView field (see first point) you end up updating an ImageView which is not being displayed anywhere; this is where not initializing said field would have given a nice indication of there being a problem. The solution is to pass the Controller instance created by the FXMLLoader to the RootLayout instance created by the other FXMLLoader.
Also, in the same class you have:
Main main = new Main();
Which is also unnecessary since the created instance of Main is both not the correct instance and is replaced by the call to #setMain(Main) almost immediately.
Assuming your FXML files (which you did not provide) are correct, the Java classes should look more like:
Main.java
public class Main extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private RootLayout rootLayoutController;
public Main() {}
#Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Help Please");
initRootLayout();
showScreen();
}
public void initRootLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
// store RootLayout instance in field so #showScreen()
// can reference it
rootLayoutController = loader.getController();
rootLayoutController.setMain(this);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void showScreen() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/sample.fxml"));
BorderPane sample = (BorderPane) loader.load();
rootLayout.setCenter(sample);
Controller controller = loader.getController();
controller.setMain(this);
// set Controller instance on RootLayout instance
rootLayoutController.setController(controller);
} catch (Exception e) {
e.printStackTrace();
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
RootLayout.java
public class RootLayout {
private Main main;
private Controller controller;
public void setMain(Main main) {
this.main = main;
}
public void setController(Controller controller) {
this.controller = controller;
}
#FXML
private void handleOpen() {
FileChooser fileChooser = new FileChooser();
// Note extensions should be prefixed with "*."
FileChooser.ExtensionFilter extensionFilter =
new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png");
fileChooser.getExtensionFilters().add(extensionFilter);
File file = fileChooser.showOpenDialog(main.getPrimaryStage());
if (file != null) {
controller.updateImage(file.toURI().toString());
}
}
}
Controller.java
public class Controller implements Initializable {
#FXML ImageView imageView; // leave uninitialized, will be injected
String imageURL;
Main main;
public void setMain(Main main) {
this.main = main;
}
public void updateImage(String url) {
if (url.length() >= 1) {
Image image = new Image(url);
imageView.setImage(image);
System.out.println(url);
} else {
System.out.println(url);
System.out.println("image invalid");
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {}
}
Note: Did not test new code.

javafx: Progress bar to show the progress of the process?

I want to show progress bar while a functionality is running. What is the best way to show it? Basically I am building a program to send multiple mails on a single click. While sending the mail I want to show progress bar while sending the mails.
The best solution in this case is using a Task.
Example:
Task<Parent> yourTaskName = new Task<Parent>() {
#Override
public Parent call() {
// DO YOUR WORK
//method to set progress
updateProgress(workDone, max);
//method to set labeltext
updateMessage(message);
}
};
//ProgressBar
ProgressBar pBar = new ProgressBar();
//Load Value from Task
pBar.progressProperty().bind(yourTaskName.progressProperty());
//New Loading Label
Label statusLabel = new Label();
//Get Text
statusLabel.setText("Loading...");
//Layout
VBox root = new VBox(statusLabel, pBar);
//SetFill Width TRUE
root.setFillWidth(true);
//Center Items
root.setAlignment(Pos.CENTER);
//SetOnSucceeded methode
yourTaskName.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
System.out.println("Finish");
}
});
//Start Thread
Thread loadingThread = new Thread(yourTaskName);
loadingThread.start();
Hope this helps you.
P.S.: The code in the task run as a Thread...
I implemented what you want last time ,If you want to show progressIndicator or progressBar when sending is running ,try this part of code
senderThreadlive = new Thread(new Runnable() {
#Override
public void run() {
try {
Platform.runLater(new Runnable() {
#Override
public void run() {
ProgressIndicator WaitingSend=new ProgressIndicator();
WaitingSend.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);
WaitingBox.getChildren().add(WaitingSend);//this is an HBOX
SendMailButton.setDisable(true);
SendMailButton.setText("sending in progress");
}
});
//call Your method of sending
SimpleMail.EmailSender.sendEmail(MailSenderTxt.getText(), MotMailTxt.getText(), DestMailTxt.getText(), ObjetMailTxt.getText(), org.jsoup.Jsoup.parse(ContentMail.getHtmlText()).text());
Platform.runLater(new Runnable() {
#Override
public void run() {
WaitingSend.setProgress(0);
WaitingSend.setVisible(false);
SendMailButton.setDisable(false);
SendMailButton.setText("Send");
}
});
} catch (AuthenticationFailedException e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
//Your popUp here
}
});
} catch (SendFailedException e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
//Your popUp here
}
});
} catch (MessagingException e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
//Your popUp here
}
});
} catch (Exception ex) {
Platform.runLater(new Runnable() {
#Override
public void run() {
//Your popUp here
}
});
}
}
});
senderThreadlive.start();
Just use javafx.scene.control.ProgressBar
Documentation:
http://docs.oracle.com/javafx/2/ui_controls/progress.htm

How to create splash screen as a Preloader in JavaFX standalone application?

I created a Preloader (based on the following tutorial) that should display a splash screen for the main application.
9.3.4 Using a Preloader to Display the Application Initialization Progress
http://docs.oracle.com/javafx/2/deployment/preloaders.htm
public class SplashScreenLoader extends Preloader {
private Stage splashScreen;
#Override
public void start(Stage stage) throws Exception {
splashScreen = stage;
splashScreen.setScene(createScene());
splashScreen.show();
}
public Scene createScene() {
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 200);
return scene;
}
#Override
public void handleApplicationNotification(PreloaderNotification notification) {
if (notification instanceof StateChangeNotification) {
splashScreen.hide();
}
}
}
I'd like to run preloader each time I run the main application in my IDE (IntelliJ IDEA).
I also followed the packaging rules for preloaders in IntelliJ:
https://www.jetbrains.com/idea/help/applications-with-a-preloader-project-organization-and-packaging.html
When I run the main application the preloader doesn't start, so I suppose I'm missing something. I'm new to Preloaders and I don't understand what is the mechanism to connect the main app with the preloader in standalone application.
You can run using LauncherImpl like this . . .
public class Main {
public static void main(String[] args) {
LauncherImpl.launchApplication(MyApplication.class, SplashScreenLoader.class, args);
}
}
And the class MyApplication would be like this . . .
public class MyApplication extends Application {
#Override
public void start(Stage primaryStage) {
....
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The IDEs aren't great at adding preloaders yet. Take a look at the Manifest in your program's jar file and make sure this line is present:
JavaFX-Preloader-Class: SplashScreenLoader
May be too late, this can also help somebody.
For me, i used JavaFX service and task to create splash screen as a Preloader in JavaFX standalone application. This, because the contexte of my project.
Create the AnchorPane and the progress Pane
#FXML
private AnchorPane anchorPane;
private MaskerPane progressPane;
public static void main(String[] args) {
launch(args);
}
#Override
public void init() throws Exception {
progressPane = new MaskerPane();
progressPane.setText(bundle.getString("root.pleaseWait"));
progressPane.setVisible(false);
AnchorPane.setLeftAnchor(progressPane, 0.0);
AnchorPane.setTopAnchor(progressPane, 0.0);
AnchorPane.setRightAnchor(progressPane, 0.0);
AnchorPane.setBottomAnchor(progressPane, 0.0);
anchorPane.getChildren().add(progressPane);
}
#Override
public void start(Stage initStage) {
//.....
initRoot();
//.....
}
Create the splash screen service as this:
private final Service<Void> splashService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
public Void call() throws Exception {
//main code, the code who take time
//or
//Thread.sleep(10000);
return null;
}
};
}
};
Start service and show/hide the progressPane on initRoot when loading the main screen:
public void initRoot() {
try {
//....
splashService.restart();
//On succeeded, do this
splashService.setOnRunning(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
//Show mask on succeed
showMask(Boolean.TRUE);
}
});
splashService.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent event) {
splashService.cancel();
//Hide mask on succeed
showMask(Boolean.FALSE);
}
});
//.....
primaryStage.show();
} catch (IOException ex) {
ex.printStackTrace();
}
}
To show/hide the progress...
showMask(boolean value){
progressPane.setVisible(value);
};

Dispose JavaFX Tasks

I have a static BorderPane with ContextMenu insight Task
Task task = new Task()
{
#Override
protected Void call() throws Exception
{
Platform.runLater(new Runnable()
{
#Override
public void run()
{
try
{
contextMenu = new ContextMenu();
MenuItem item1 = new MenuItem("About");
item1.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
System.out.println("About");
}
});
MenuItem item2 = new MenuItem("Preferences");
item2.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
System.out.println("Preferences");
}
});
MenuItem item3 = new MenuItem("Close");
item3.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
}
});
contextMenu.getItems().addAll(item1, item2, item3);
bp.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>()
{
#Override
public void handle(ContextMenuEvent event)
{
contextMenu.show(bp, event.getScreenX(), event.getScreenY());
event.consume();
}
});
bp.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent event)
{
contextMenu.hide();
}
});
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
}
}
});
return null;
}
};
new Thread(task).start();
I noticed that when I close the component which holds the BorderPane the Java Threads are not disposed they are still initialized into the memory. I'm not sure is this caused by the static BorderPane. After the Task is completed the Java Thread should be disposed. Any idea why is this happening?
The problem is not a Task, but the anonymous classes in your Runnable.
In the next piece of code:
bp.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>()
{
#Override
public void handle(ContextMenuEvent event) {
//...
}
});
you introduce an anonymous class extending EventHandler which holds inner link to a Runnable. To solve that you can use nested static class instead.
P.S.: Unfortunately you can't make anonymous class static in Java, see Is it possible to make anonymous inner classes in Java static?

Context Menu in JavaFX Task

Following this topic Context menu insight JavaFX Task I want to create Context Menu in JavaFX Task. I tested this code:
static private StringBuilder stringBuilder = new StringBuilder();
private static ContextMenu contextMenu;
private static CountDownLatch menuCreated = new CountDownLatch(1);
static synchronized void writeString(String s)
{
stringBuilder.append(s).append("\n");
}
public static BorderPane init(BorderPane bp) throws Exception
{
System.out.println("***** CALLED");
Task task = new Task()
{
#Override
protected Void call() throws Exception
{
writeString("Task started");
writeString(Thread.currentThread().getName() + " is fx thread: "
+ Platform.isFxApplicationThread());
Platform.runLater(new Runnable()
{
#Override
public void run()
{
writeString(Thread.currentThread().getName() + " is fx thread: "
+ Platform.isFxApplicationThread());
try
{
contextMenu = new ContextMenu();
contextMenu.setId("Test ID");
writeString("Created context menu");
menuCreated.countDown();
}
catch (Exception ex)
{
writeString(ex.getMessage());
ex.printStackTrace();
}
finally
{
writeString("Test");
}
}
});
writeString("Task finished");
return null;
}
};
new Thread(task).start();
MenuItem item1 = new MenuItem("About");
item1.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
System.out.println("About");
}
});
MenuItem item2 = new MenuItem("Preferences");
item2.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
System.out.println("Preferences");
}
});
MenuItem item3 = new MenuItem("Close");
item3.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
//flow.getChildren().remove(bp);
}
});
contextMenu.getItems().addAll(item1, item2, item3);
bp.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>()
{
#Override
public void handle(ContextMenuEvent event)
{
//contextMenu.hide();
System.out.println("*********************** Shown Context Menu ***!!!!!!!");
contextMenu.show(bp, event.getScreenX(), event.getScreenY());
event.consume();
}
});
bp.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent event)
{
contextMenu.hide();
}
});
menuCreated.await();
return bp;
}
With this code I set Context Menu for BorderPane. When I click with the right mouse button I see the debug message *********************** Shown Context Menu ***!!!!!!! but there is no context menu. Can you help me to fix this code?

Resources