Reputation: 556
I have in main class:
public void start(Stage primaryStage) throws Exception {
Thread timeCheckThread = new Thread() {
@Override
public void run() {
try{
while (!done) {
System.out.println("Running!!");
System.out.println();
currentDate = LocalDate.now();
if (!oldDate.equals(currentDate)) {
index++;
saveData();
System.out.println("Saved!");
}
currentThread().sleep(5000);
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
};
timeCheckThread.start();
stage = primaryStage;
stage.initStyle(StageStyle.TRANSPARENT);
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = (Parent) loader.load();
StackPane stackPane = new StackPane(root);
stackPane.setStyle("-fx-background-color: rgba(0,0,0,0);");
Scene scene = new Scene(stackPane, 312, 212);
scene.setFill(Color.TRANSPARENT);
stage.setScene(scene);
Controller controller = loader.<Controller>getController();
controller.registerStage(stage);
stage.show();
}
//launch 'start'
public static void main(String[] args) {
launch(args);
}
and in Controller class:
public void exitButtonClicked() {
Platform.exit();
}
I want to pass a boolean from method exitButtonClicked
to the main class so that I can end the loop of while(!done)
. What is the efficient approach to accomplish this? Is, having a setter
for done
in a main method, and invoking that setter
from an instance of Main
class in Controller
class, a good method?
Upvotes: 2
Views: 156
Reputation: 12346
There are two issues. Your controller needs access to the variables, and you have a 5s sleep. One way to do it, without passing around an instance of your main class is to make a static utility method.
class Main extends Application{
static volatile boolean done = false;
static Thread timeCheckThread;
static void applicationIsExiting(){
done = true;
timeCheckThread.interrupt();
}
}
Then when you create the time check thread assign it to the static variable:
timeCheckThread = new Thread() { ...
The method in your controller would have a call the utility method.
public void exitButtonClicked() {
Platform.exit();
Main.applicationIsExiting();
}
Upvotes: 1
Reputation: 9648
Create a final class or interface with a boolean. Set/Get this boolean wherever you need.
public final class foo {
public static boolean flag = false;
}
In your Controller Class:
foo.flag = true;
In your Main Class:
while(!foo.flag) {
/* Do Something */
}
Upvotes: 2