I can't show a 'Wait' screen when I need to wait for a thread to be finished - multithreading

I need to show some kind of animation(progress indicator) when a task takes some time to complete.
This is the code for my wait screen:
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
public class scrWaitForm extends Form {
public static scrWaitForm create() {
return new scrWaitForm();
}
private final Gauge gagProgressBar;
private final StringItem strMensaje;
protected scrWaitForm() {
super("Procesando");
this.gagProgressBar = new Gauge("", false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING);
this.gagProgressBar.setLayout(Item.LAYOUT_CENTER| Item.LAYOUT_VCENTER);
this.append(gagProgressBar);
this.strMensaje=new StringItem("Loading...", null);
this.append(strMensaje);
}
}
And this is how I show it :
public void showWaitForm() {
scrWaitForm frmWaitForm = scrWaitForm.create();
mDisplay.setCurrent(frmWaitForm);
}
As you can see, it is very simple. I only use a Gauge. The problem is that the wait screen won't be displayed if I need to wait for a thread to be finished so that I can use some operation results(from the thread) in other operations. However, if I only call the wait screen without waiting for the thread to complete it works as expected.
This is what I initially did:
thrLoadCustomers load = new thrLoadCustomers(rmsCustomers, url);
Thread t = new Thread(load);
showWaitForm()
t.start();
try {
t.join();
} catch (InterruptedException ex) {
}
But then with the help of Mister Smith I ended up using something like this :
WSResult result = new WSResult();
//Start thread here
new Thread(new LoadCustomersTask(result)).start();
//This is old school thread sync.
synchronized(result){
showWaitForm();
while(!result.isCompleted()){
result.wait();
}
}
Am I doing something wrong?? How do you normally show an animation or another screen so that user sees that something is taking place and don't intend to invoke the same action over and over again.
Thanks in advance.

Related

Why does my RotateTransition throw errors after it runs for the first time?

Warning: This is my first time using threads and my first time trying out an animation. Please bear with me.
I want to rotate an ImageView. I set up a thread for it:
public class ThreadAnimation extends Thread
{
private ImageView iv;
private RotateTransition rt;
public ThreadAnimation(ImageView iv)
{
this.iv = iv;
}
#Override
public void run()
{
while (true)
{
RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);
r.play();
try
{
sleep(100);
} catch (InterruptedException e)
{
return;
}
}
}
}
I call this inside my controller class, upon pressing a Button.
animation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle (ActionEvent abschicken)
{
ThreadAnimation thread = null; //ANIMATION PIZZA
if (thread == null)
{
thread = new ThreadAnimation(olivenview);
thread.start();
}
}
});
My ImageView olivenview will rotate just like I wanted it to. However it takes quite a long time until it seems to stop (I can see it because the button triggering it still looks triggered for a while) and when I go ahead to press it a second time afterwards, I get a nonstop error stream with a lot of null pointer exceptions. I am very clueless, can anyone help me out? Is this due to my Thread Setup or does the problem lie somewhere else (in code that I didn't post here)?
I believe you do not need threads for this. Notice the .play() method returns immediately and the animation will run in the background.
That being said, try this.
...
//Create your rotation
final RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);
//When the button is pressed play the rotation. Try experimenting with .playFromStart() instead of .play()
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent action) {
r.play();
}
});
...
On an other note I recommend switching to java 8 so that you can use lambda expressions instead of the anonymous class!

Using Thread.sleep to get waiting effect in JavaFX [duplicate]

This question already has answers here:
JavaFX periodic background task
(6 answers)
Closed 5 years ago.
I want to achieve something like this: user press the login button and then label shows:
"Connecting."
0.5 sec time interval
"Connecting.."
0.5 sec time interval
"Connecting..."
etc
Just a visual effect that indicates something is actually going on "under the hood".
All I managed to get wasn't quite what I was expecting. I click the button, wait 1.5 sec and then I got "Connecting...", missing 2 previous steps.
First, my Status class
public class Status {
private static StringProperty status = new SimpleStringProperty();
public static void setStatus(String newStatus) {
status.setValue(newStatus);
}
public static String getStatus() {
return status.getValue();
}
public static StringProperty get() {
return status;
}
}
and my LoginView class
public class LoginView extends Application {
private Button loginButton = new Button("Log in");
private Label statusLabel;
private void createLabels() {
statusLabel = new Label(Status.getStatus());
statusLabel.textProperty().bind(Status.get());
}
}
private void createButtons() {
loginButton.setOnAction(e -> {
try {
Status.setStatus("Connecting.");
Thread.sleep(500);
Status.setStatus("Connecting..");
Thread.sleep(500);
Status.setStatus("Connecting...");
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
});
}
Run a Task from a different thread. Task allows you to update it's message property on the JavaFX application thread that should be used to update the GUI and must not be blocked by long-running tasks, since it's responsible for rendering:
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws InterruptedException {
updateMessage("Connecting.");
Thread.sleep(500);
updateMessage("Connecting..");
Thread.sleep(500);
updateMessage("Connecting...");
Thread.sleep(500);
return null;
}
};
// bind status to task's message
Status.get().bind(task.messageProperty());
// run task on different thread
new Thread(task).start();
You should do animations with the Timeline API. Have a look here:
https://docs.oracle.com/javase/8/javafx/api/javafx/animation/Timeline.html
Basically you just define KeyFrames at 0.5 seconds distance and set the value of the text to add a another dot. You can also make it repeat indefinitely until the connection is established to get cyclic animation.
Another way is to make a SequentialTransition which will have two PauseTransitions of 0.5 seconds.
BTW in your code you pause the main UI thread and that is why you can’t see the animation.

Is it possible to show a Node during FX thread

I'm making a program which reads text files. What I would like to do is show an arbitrary node (Alert or other Node) which is created in separate thread before or during the file reading. I tried using Task and Platform.runLater() like this:
if (filetoopen != null)
{
Platform.runLater(new Runnable() {
#Override
void run() {
Alert alert=new Alert(Alert.AlertType.INFORMATION)
alert.setHeaderText('TEST')
}
})
//method to read the file
Tools.convertFromFile(filetoopen,newredactor)
lastDirectory = filetoopen.getParentFile()
}
I'd like to show an Alert or progress bar of reading the file, but the Control initializes after the reading is finished. So, is it possible to show a Node with a progress bar while the file is being read? Or the Runnable I create will always be executed in the end?
Edit: an attempt with Task:
class Alerter extends Task{
Alerter(File f,Editor e)
{
file=f
editor=e
}
File file
Editor editor
#Override
protected Object call() throws Exception {
Dialog dialog=new Dialog()
DialogPane dp=dialog.getDialogPane()
dp.setHeaderText('TEST')
dp.getButtonTypes().add(new ButtonType('Cancel',ButtonBar.ButtonData.CANCEL_CLOSE))
dialog.setOnCloseRequest(new javafx.event.EventHandler<DialogEvent>() {
#Override
void handle(DialogEvent event) {
dialog.close()
}
})
dialog.show()
Tools.convertFromFile(file,editor)
return null
}
}
The dialog still initializes after Tools.convertFromFile.
There are two threading rules in JavaFX (and in almost every other UI toolkit):
Changes to the scene graph (i.e. creating new scenes or windows, or changing the state of nodes already displayed) must be done on the FX Application Thread.
Long-running processes should be performed on a background thread (i.e. not the FX Application Thread), otherwise the UI will become unresponsive.
Your first code block violates the second rule (probably, you haven't shown much context) and your second code block violates the first rule.
So basically you need to:
Show the dialog from the FX Application Thread
Start a new thread which processes the file in the background
From the new thread, schedule any changes to the new UI on the FX Application Thread
When processing the file finishes, update the UI on the FX Application Thread
You can use Platform.runLater(...) to schedule code to run on the FX Application Thread, but the Task class provides more convenient API for these updates.
So:
// set up and show dialog:
ProgressBar progressBar = new ProgressBar();
DialogPane dialogPane = new DialogPane();
dialogPane.getButtonTypes().setAll(ButtonType.OK);
dialogPane.setHeaderText("Processing file");
dialogPane.setContent(progressBar);
dialogPane.lookupButton(ButtonType.OK).setDisable(true);
Dialog dialog = new Dialog();
dialog.setDialogPane(dialogPane);
dialog.show();
// create task:
Task<Void> task = new Task<Void>() {
#Override
public Void call() throws Exception {
Tools.convertFromFile(file, editor);
// can call updateProgress(...) here to update the progress periodically
return null ;
}
};
// update progress bar with progress from task:
progressBar.progressProperty().bind(task.progressProperty());
// when task completes, update dialog:
task.setOnSucceeded(event -> {
dialogPane.lookupButton(ButtonType.OK).setDisable(false);
progressBar.progressProperty().unbind();
progressBar.setProgress(1);
dialogPane.setHeaderText("Processing complete");
});
// handles errors:
task.setOnFailed(event -> {
dialogPane.lookupButton(ButtonType.OK).setDisable(false);
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
dialogPane.setHeaderText("An error occurred");
});
// run task in background thread:
Thread thread = new Thread(task);
thread.start();
Note here that your Tools.convertFromFile(...) method is called from a background thread, so it must not update the UI (or at least any calls in that method that do update the UI must be wrapped in Platform.runLater(...)).
Here is a complete SSCCE (which just sleeps as a demo of a long-running process):
import java.util.Random;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class TaskWithProgressDemo extends Application {
#Override
public void start(Stage primaryStage) {
Button button = new Button("Start process");
button.setOnAction(e -> {
button.setDisable(true);
// set up and show dialog:
ProgressBar progressBar = new ProgressBar();
DialogPane dialogPane = new DialogPane();
dialogPane.getButtonTypes().setAll(ButtonType.OK);
dialogPane.setHeaderText("Processing file in progress");
dialogPane.setContent(progressBar);
dialogPane.lookupButton(ButtonType.OK).setDisable(true);
Dialog<Void> dialog = new Dialog<Void>();
dialog.setDialogPane(dialogPane);
dialog.show();
// create task:
Task<Void> task = new Task<Void>() {
#Override
public Void call() throws Exception {
Random rng = new Random();
for (int i = 0 ; i <= 100 ; i++) {
Thread.sleep(rng.nextInt(40));
updateProgress(i, 100);
}
if (rng.nextBoolean()) {
System.out.println("Simulated error");
throw new Exception("An unknown error occurred");
}
return null ;
}
};
// update progress bar with progress from task:
progressBar.progressProperty().bind(task.progressProperty());
// when task completes, update dialog:
task.setOnSucceeded(event -> {
dialogPane.lookupButton(ButtonType.OK).setDisable(false);
button.setDisable(false);
progressBar.progressProperty().unbind();
progressBar.setProgress(1);
dialogPane.setHeaderText("Processing complete");
});
// handles errors:
task.setOnFailed(event -> {
dialogPane.lookupButton(ButtonType.OK).setDisable(false);
button.setDisable(false);
progressBar.progressProperty().unbind();
progressBar.setProgress(0);
dialogPane.setHeaderText("An error occurred");
});
// run task in background thread:
Thread thread = new Thread(task);
thread.start();
});
StackPane root = new StackPane(button);
root.setPadding(new Insets(20));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
So I finally figured it out. I had to move both my file loading code and progress update to a Task, so it wouldn't block FX thread. The indicator shows progress of loading a file.
Edit: to achieve progress display in a separate non-blocking window, must use a new Stage instead of anything else.

repainting multiple JPanel from a single "control" panel

so i'm trying to set up an application where i have multiple panels inside a jframe. lets say 3 of them are purely for display purposes, and one of them is for control purposes. i'm using a borderLayout but i don't think the layout should really affect things here.
my problem is this: i want the repainting of the three display panels to be under the control of buttons in the control panel, and i want them to all execute in sync whenever a button on the control panel is pressed. to do this, i set up this little method :
public void update(){
while(ButtonIsOn){
a.repaint();
b.repaint()
c.repaint();
System.out.println("a,b, and c should have repainted");
}
}
where a,b, and c are all display panels and i want a,b,and c to all repaint continously until i press the button again. the problem is, when i execute the loop, the message prints in an infinite loop, but none of the panels do anything, ie, none of them repaint.
i've been reading up on the event dispatch thread and swing multithreading, but nothing i've found so far has really solved my problem. could someone give me the gist of what i'm doing wrong here, or even better, some sample code that handles the situation i'm describing? thanks...
The java.util.concurrent package provides very powerful tools for concurrent programing.
In the code below, I make use of a ReentrantLock (which works much like the Java synchronized keyword, ensuring mutually exclusive access by multiple threads to a single block of code). The other great thing which ReentrantLock provides are Conditions, which allow Threads to wait for a particular event before continuing.
Here, RepaintManager simply loops, calling repaint() on the JPanel. However, when toggleRepaintMode() is called, it blocks, waiting on the modeChanged Condition until toggleRepaintMode() is called again.
You should be able to run the following code right out of the box. Pressing the JButton toggle repainting of the JPanel (which you can see working by the System.out.println statements).
In general, I'd highly recommend getting familiar with the capabilities that java.util.concurrent offers. There's lots of very powerful stuff there. There's a good tutorial at http://docs.oracle.com/javase/tutorial/essential/concurrency/
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RepaintTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel()
{
#Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
// print something when the JPanel repaints
// so that we know things are working
System.out.println( "repainting" );
}
};
frame.add( panel );
final JButton button = new JButton("Button");
panel.add(button);
// create and start an instance of our custom
// RepaintThread, defined below
final RepaintThread thread = new RepaintThread( Collections.singletonList( panel ) );
thread.start();
// add an ActionListener to the JButton
// which turns on and off the RepaintThread
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
thread.toggleRepaintMode();
}
});
frame.setSize( 300, 300 );
frame.setVisible( true );
}
public static class RepaintThread extends Thread
{
ReentrantLock lock;
Condition modeChanged;
boolean repaintMode;
Collection<? extends Component> list;
public RepaintThread( Collection<? extends Component> list )
{
this.lock = new ReentrantLock( );
this.modeChanged = this.lock.newCondition();
this.repaintMode = false;
this.list = list;
}
#Override
public void run( )
{
while( true )
{
lock.lock();
try
{
// if repaintMode is false, wait until
// Condition.signal( ) is called
while ( !repaintMode )
try { modeChanged.await(); } catch (InterruptedException e) { }
}
finally
{
lock.unlock();
}
// call repaint on all the Components
// we're not on the event dispatch thread, but
// repaint() is safe to call from any thread
for ( Component c : list ) c.repaint();
// wait a bit
try { Thread.sleep( 50 ); } catch (InterruptedException e) { }
}
}
public void toggleRepaintMode( )
{
lock.lock();
try
{
// update the repaint mode and notify anyone
// awaiting on the Condition that repaintMode has changed
this.repaintMode = !this.repaintMode;
this.modeChanged.signalAll();
}
finally
{
lock.unlock();
}
}
}
}
jComponent.getTopLevelAncestor().repaint();
You could use SwingWorker for this. SwingWorker was designed to perform long running tasks in the background without blocking the event dispatcher thread. So, you need to extend SwingWorker and implement certain methods that will make sense to you. Note that all long running action should happen in the doInBackground() method, and the Swing UI elements should be updated only on the done() method.
So here is an example :
class JPanelTask extends SwingWorker<String, Object>{
JPanel panel = null;
Color bg = null;
public JPanelTask(JPanel panel){
this.panel = panel;
}
#Override
protected String doInBackground() throws Exception {
//loooong running computation.
return "COMPLETE";
}
#Override
protected void done() {
panel.repaint();
}
}
Now, in your "control" button's action performed event, you could do the following :
controlButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JPanelTask task1 = new JPanelTask(panel1);
task1.execute();
JPanelTask task2 = new JPanelTask(panel2);
task2.execute();
//so on..
}
});
Another way is using javax.swing.Timer. Timer helps you to fire a change to your ui elements in a timely fasthion.This may not be the most appropriate solution. But it gets the work done too.
Again you should be careful about updating UI elements in right places.

Working with threads in blackberry

I am using threads in blackberry to perform web service calls. I want to get notified as soon as the call gets a response back. I was using
Handlers
in android. I didnt find anything similar in blackberry.
Here is the code I am using to run the thread
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
How can I get a notification after the thread finished running?
How can I do this in blackberry?
Thanks
Added more Information : Thanks for your reply. Its really
informative. Let me explain a bit more on my issue. I have a
webservice call which is running on a thread. As soon as I get the
reply back from server I want to execute the next function(next call
to server) which is based on the response from the previous call.So I need to wait until I get a response back. Also
at them same time I need to show a activity indicator on screen. I was
using handler for this in android. I am looking for something similar
on blackberry.
So your question essentially is this
One thread does the job while the other thread waits for completion
The first thread completes the job and "notifies" the second thread.
This is a simple producer consumer problem. Here is the code how you can solve this.
class JobResult
{
boolean done = false;
}
JobResult result = new JobResult();
class Worker extends Thread
{
JobResult _result;
public Worker( JobResult result )
{
_result = result
}
public void run()
{
// Do some very long job
synchronized( _result )
{
// modify result
_result.done = true;
_result.notify();
}
}
}
public class Waiter extends Thread
{
JobResult _result;
public Waiter( JobResult result )
{
_result = result;
}
public void run()
{
synchroinzed( _result ){
while(! _result.done)
{
this.wait();
}
}
// Wait is over. You can do something now.
}
}
As I got the Zach's question - he asks how to execute some code that involves UI changes (something like showing an info popup or closing the progress popup) upon a background thread completion. On Android a Handler created on the UI thread is often used for that purpose.
In BB you can use another way which is similar to Swing on desktop Java. When you need some code to be executed on the UI thread you wrap it in a Runnable and pass to one of the following methods:
// Puts runnable object into this application's event queue,
// and waits until it is processed.
Application.invokeAndWait(Runnable runnable)
// Puts runnable object into this application's event queue.
Application.invokeLater(Runnable runnable)
// Puts runnable object into this application's event queue
// for repeated execution.
Application.invokeLater(Runnable runnable, long time, boolean repeat)
So the behaviour of the above calls is similar to what Handler.post(Runnable r) (and the like) does.
Note, you can always get a handle to your Application instance by a static call Application.getApplication().
So in the end of a background thread it is safe to do something like this:
Application.getApplication().invokeLater(new Runnable() {
public void run() {
progressScreen.close();
Dialog.alert("I am finished!");
}
});
It is similar to Android's:
handler.post(new Runnable() {
public void run() {
progressScreen.dismiss();
showDialog(DIALOG_TASK_FINISHED_ID);
}
});
Android has a much rich multi threading primitives. But you can achieve the same even in Blackberry with equal elegance. The solution I provide below is essentially the same as previous, but with a minor change. Waiter thread can be replaced with built-in utility to perform painting on UI thread using UiApplicaiton's invokeLater method. You don't actually need to "notify" anyone but just update the UI once a particular task is completed. Check the docs for more info.
Anyway, you can model your code along the lines:
class ProgressScreen extends FullScreen
{
LabelField _label;
public void start()
{
}
public void setMessage( final String message )
{
UiApplication.getApplication(
UiApplication.invokeLater(
new Runnable() {
_label.setText( message );
}
)
);
}
public void dismiss()
{
this.close();
}
}
interface WebserviceTask
{
int STATUS_CONDITIONS_NOT_SATISFIED = -3;
int STATUS_NET_ERR = -2;
int STATUS_FAILURE = -1;
int STATUS_SUCCESS = 0;
public int invoke();
}
public class Updater extends Thread
{
final int NUM_TASKS = 10;
WebServiceTask tasks[] = new WebServiceTask[ NUM_TASKS ];
WebServiceTask tasks[0] = new WebServiceTask(){
public int invoke()
{
int retCode = 0;
// invoke a particular web service
return STATUS_SUCCESS;
}
}
public void run()
{
ProgressScreen progress = new ProgressScreen();
progress.start();
for( int i=0; i < NUM_TASKS; i++ )
{
int retcode;
WebServiceTask t = tasks[i];
retcode = t.invoke();
String mesg;
switch( retcode )
{
case STATUS_SUCCESS: { mesg ="Task successfully completed!";} break;
case STATUS_NET_ERR: { mesg ="Could not connect to network";} break;
}
progress.setMessage(message);
}
progress.dismiss();
}
}
Note that I have provided only the stubs to give you an idea how you may accomplish. Let us know how it goes.

Resources