JavaFX 2 busy indicator cursor - javafx-2

I'm trying to change the cursor to indicate that the program is busy. It seems like this should be pretty simple, but I haven't been able to get it to work correctly and after searching for several hours, I haven't come up with the solution. Here's what I'm trying to do.
public class ButtonTest extends Application {
#Override
public void start(Stage primaryStage) {
final StackPane root = new StackPane();
primaryStage.setScene(new Scene(root, 200, 150));
Button button = new Button();
button.setText("Button");
root.getChildren().add(button);
primaryStage.show();
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// Set the cursor to the wait cursor.
root.setCursor(Cursor.WAIT);
// Do some work.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Set the cursor back to the default.
root.setCursor(Cursor.DEFAULT);
}
});
}
public static void main(String[] args) {
launch(args);
}
}
If I comment out the setCursor(Cursor.DEFAULT), after I press the button it waits 5 seconds then changes the cursor to the wait cursor. So it seems like it waiting until after the sleep, then executing setCursor(Cursor.WAIT), immediately followed by the setCursor(Cursor.DEFAULT). What am I missing?

You're sleeping the main UI thread which is the same thread that's supposed to change the cursor shape. You need to kick off your sleep (or whatever expensive operation) on a background thread, while the main UI thread exits the handle method and returns to the UI event loop so that the cursor change can become active.

Have you ever tried Platform.runLater for this:
It should work like this:
primaryStage.getScene().setCursor(Cursor.WAIT);
Platform.runLater(new Runnable() {
#Override
public void run() {
doSomethingInteresting();
primaryStage.getScene().setCursor(Cursor.DEFAULT);
}
});
The idea here is simple: in the original event just the mouse shape is defined and a new event is scheduled which will perform the action directly after this.

Related

JavaFX - Cancel Task doesn't work

In a JavaFX application, I have a method which takes a long time on large input. I'm opening a dialog when it is loading and I'd like the user to be able to cancel/close out the dialog and the task will quit. I created a task and added its cancellation in the cancel button handling. But the cancellation doesn't happen, the task doesn't stop executing.
Task<Void> task = new Task<Void>() {
#Override
public Void call() throws Exception {
// calling a function that does heavy calculations in another class
};
task.setOnSucceeded(e -> {
startButton.setDisable(false);
});
}
new Thread(task).start();
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
System.out.println("Button handled");
task.cancel();
}
);
Why isn't the task getting canceled when the button clicked?
You have to check on the cancel state (see Task's Javadoc). Have a look at this MCVE:
public class Example extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
new AnotherClass().doHeavyCalculations(this);
return null;
}
};
Button start = new Button("Start");
start.setOnMouseClicked(event -> new Thread(task).start());
Button cancel = new Button("Cancel");
cancel.setOnMouseClicked(event -> task.cancel());
primaryStage.setScene(new Scene(new HBox(start, cancel)));
primaryStage.show();
}
private class AnotherClass {
public void doHeavyCalculations(Task<Void> task) {
while (true) {
if (task.isCancelled()) {
System.out.println("Canceling...");
break;
} else {
System.out.println("Working...");
}
}
}
}
}
Note that…
You should use Task#updateMessage(String) rather than printing to System.out, here it's just for demonstration.
Directly injecting the Task object creates a cyclic dependency. However, you can use a proxy or something else that fits your situation.

Binding Properties and using them during lengthy operations

In my JavaFX Application I want to disable a couple of Buttons during a refresh of the data from a database.
I am using the disableProperty of the Buttons I want to disable.
Here is the basic JavaFX Application, modefied to illustrate my point:
public class BindLengthy extends Application {
BooleanProperty disable = new SimpleBooleanProperty(false);
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.disableProperty().bind(disable);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
disable.set(true);
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(BindLengthy.class.getName()).log(Level.SEVERE, null, ex);
}
btn.setText("Done");
}
});
//Do all the other stuff that needs to be done to launch the application
//Like adding btn to the scene and so on...
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
When executed, on the click the Button stays in the "fired" mode, waits for 5 Seconds and then changes text and disables. While I want the text to change later, I want to disableProperty Change to take effect immediately!
I tried putting the lengthy operation, represented by Thread.sleep(5000) into a task and start it on a new Thread(task), but then obviously the text is changes before the Thread awakens.
I can't put the btn.setText("Done")into the Threadas it wouldn't be executed on the JavaFX-Thread(which it needs to). So I tried joining the Thread, yet that gives the same result as not putting it into an extra Thread as well.
How can I force the diableProperty to register the new value before executing my long operation?
Use a Task and use its onSucceeded handler to update the UI:
public class BindLengthy extends Application {
BooleanProperty disable = new SimpleBooleanProperty(false);
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.disableProperty().bind(disable);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
disable.set(true);
Task<String> task = new Task<String>() {
#Override
public String call() throws Exception {
Thread.sleep(5000);
return "Done" ;
}
});
task.setOnFailed(e ->
Logger.getLogger(BindLengthy.class.getName())
.log(Level.SEVERE, null, task.getException()));
task.setOnSucceeded(e -> {
btn.setText(task.getValue());
disable.set(false);
});
Thread t = new Thread(task);
t.setDaemon(true);
t.start();
}
});
//Do all the other stuff that needs to be done to launch the application
//Like adding btn to the scene and so on...
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

JavaFX: How to make an looping thread without freezing application?

How do I go about making a thread within JavaFX? I've looked around and no answers are clear/want I need, which is basicly the same as Java's Thread Runnable, which is not conpatible with JavaFx unless it's for a background task.
The basic start application class I have:
public class Main extends Application {
private Stage stage;
private AnchorPane rootLayout;
#Override
public void start(Stage stage) {
this.stage = stage;
this.stage.setTitle("Main");
setLayout();
}
private void setLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/View.fxml"));
rootLayout = (AnchorPane) loader.load();
Scene scene = new Scene(rootLayout);
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
I need a JavaFX Thread that'll keep changing the visibility of a button without freezing/pausing the application while it's running, how do I go about doing this?
Edit: I need this but for a JavaFX app:
public void run(){
while (true){
if (button.isVisible)
button.setVisibility(false);
else
button.setVisibility(true);
Thread.sleep(1000);
}
}

JavaFX: How to disable a button for a specific amount of time?

I want to disable a button for a specific time in JavaFX application. Is there any option to do this? If not, is there any work around for this?
Below is my code in application. I tried Thread.sleep, but i know this is not the good way to stop the user from clicking on next button.
nextButton.setDisable(true);
final Timeline animation = new Timeline(
new KeyFrame(Duration.seconds(delayTime),
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
nextButton.setDisable(false);
}
}));
animation.setCycleCount(1);
animation.play();
You could use the simple approach of a thread that provides the relevant GUI calls (through runLater() of course):
new Thread() {
public void run() {
Platform.runLater(new Runnable() {
public void run() {
myButton.setDisable(true);
}
}
try {
Thread.sleep(5000); //5 seconds, obviously replace with your chosen time
}
catch(InterruptedException ex) {
}
Platform.runLater(new Runnable() {
public void run() {
myButton.setDisable(false);
}
}
}
}.start();
It's perhaps not the neatest way of achieving it, but works safely.
You could also be using the Timeline:
final Button myButton = new Button("Wait for " + delayTime + " seconds.");
myButton.setDisable(true);
final Timeline animation = new Timeline(
new KeyFrame(Duration.seconds(delayTime),
new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
myButton.setDisable(false);
}
}));
animation.setCycleCount(1);
animation.play();
The method to disable a JavaFX control is:
myButton.setDisable(true);
You can implement the time logic programmatically in any way you wish, either by polling a timer or by having this method invoked in response to some event.
If you have created this button instance through FXML in SceneBuilder, then you should assign the button an fx:id so that its reference is automatically injected into your controller object during the loading of the scene graph. This will make it easier for you to work with in your controller code.
If you have created this button programmatically, then you'll already have its reference available in your code.
Or you could use a Service and bind the running property to the disableProperty of the button do you want to disable.
public void start(Stage stage) throws Exception {
VBox vbox = new VBox(10.0);
vbox.setAlignment(Pos.CENTER);
final Button button = new Button("Your Button Name");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Service<Void> service = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
Thread.sleep(5000);//Waiting time
return null;
}
};
}
};
button.disableProperty().bind(service.runningProperty());
service.start();
}
});
vbox.getChildren().addAll(button);
Scene scene = new Scene(vbox, 300, 300);
stage.setScene(scene);
stage.show();
}
But the Timeline solution given by Uluk Biy, looks more elegant.

onClick and setImagResource [Android] API 10

I'm trying to understand why it's occuring me the following problem.
I have an ImageView and i set an image to it, then i setup a onClickListener to it, so when you click to image it change the image (to a new image) by image01.setImageResource(R.drawable.newImage). After that i call a method where i check a condition, if it is true i change the image again to the default one.
But I can't see the change because it change immediately. I also insert a sleep to make it slower.
(By default in the xml code i setted the image to oldImage)
Ok... maybe it's not clear.. so let's see the CODE:
private void myMethod(){
ImageView image01 = (ImageView) findViewById(R.id.image01);
image01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//When you click on image it change!
image01.setImageResource(R.drawable.newImage);
checkImg(image01);
}
});
}
private void checkGame(ImageView img){
try{
Thread.sleep(1000);
if(condition)
img.setImageResource(R.drawable.oldImage);
}catch (Exception e) {
e.printStackTrace();
}
}
I saw immediately the oldImage. What's the problem?
Is it possible that the view change are not applied in myMethod() until all methods inside it will terminate?
Thanks in advance
Using Thread.sleep() method, you are actually making wait to main UI thread. The main UI thread's methods are not synchronized. Be aware of that.
Please go through the developers.android site for using of threads painlessly... before seeing the your useful code.
private void myMethod(){
ImageView image01 = (ImageView) findViewById(R.id.image01);
image01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//When you click on image it change!
image01.setImageResource(R.drawable.newImage);
checkGame(image01);
}
});
}
private void checkGame(ImageView img){
try{
// Thread.sleep(1000);
if(condition)
image01.postDelayed(new Runnable() {
#Override
public void run() {
image01.setImageResource(R.drawable.oldImage);
}
}, 2000);
}catch (Exception e) {
e.printStackTrace();
}
}

Resources