So, I have seen people struggle pausing their scripts while their gui is open.
Sometimes they try using a boolean
public void onStart(){
gui.initComponents()
pause = true;
}
public int onLoop(){
if(pause == false){
//do stuff
}
}
In theory it works, but its not really what you want to do, do you?
You essentially want to halt the scripts thread from working until the gui is closed or the start button is pressed, because you only want it to start doing stuff only after the user has his settings done
so this is where synchronization of objects comes into play.
we just add this to your main class:
public class Main extends Script{
Object lock = new Object();
public void onStart(){
GUI.initComponents();
synchronized(lock){
lock.wait();
}
}
public int onLoop(){
return 100;
}
}
And it halts the thread.
When a thread invokes a synchronized statement, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns.
Every object has an intrinsic lock associated with it. A thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.
But now you are asking how is my gui functioning if my script is halted? Its because the gui will be handled on another thread which the synchronized statement doesn't affect.
Alright, so we know we halted our script thread, now what?
We need to start it again, so we know our gui is handled on another thread which is not affected by the synchronized statement, which in term would mean the thread is "free" to do anything with the object
So we just do this on the button:
JButton button = new JButton("Start");
frame.add(button);
button.addActionListener{e ->{
synchronized(main.lock){
main.lock.notify();
}
frame.setVisible(false);
}
as we notify the object, the object now releases its intrinsic lock and lets the script thread run as normal as before the lock.
Hope you learned something. If I have made mistakes feel free to correct me