Wait for button press JButton

actionlistener, java, jlabel, jpanel, swing

Solution

You can wait by putting thread to sleep.

while(inBattle == false){
    try {
       Thread.sleep(200);
    } catch(InterruptedException e) {
    }
}
// perform operations when inBattle is true

Also don't forget to make inBattle volatile

Problem

I am looking for a way of making my program wait until a button is pressed to continue the function. In my main function i am calling a function which shows my basic GUI using JPanel, buttons and labels. ofcourse, it shows the GUI and ends that function not allowing me to alter the GUI. ``` public static Player player = new Player(); public static Gui gui = new Gui(); public static boolean inMain = true; public static boolean inBattle = false; public static void main(String[] args){ showMainGui(); } ``` I think what im looking for is something that will look like this: ``` public static void main(String[] args){ showMainGui(); while(inBattle == false){ // wait until inBattle changes } } ``` That while loop will loop and wait until a button created in showMainGui changes inBattle to true. How could i do this exactly? This is rather confusing me. My goal is to click a JButton and the buttons change to different buttons My action listener for my button created on the showMainGui(); ``` public class Hunt implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { MainClass.inBattle = true; } } ``` and here is my showMainGui() method ``` public static void showMainGui(){ gui.panel.add(gui.healthLabel); gui.panel.add(gui.pbsLabel); gui.panel.add(gui.staminaLabel); gui.panel.add(gui.levelLabel); //Adding initial buttons gui.panel.add(gui.exploreButton); gui.panel.add(gui.huntButton); gui.panel.add(gui.newsLabel); gui.panel.add(gui.effectLabel); updateGui(); } ```

Original source

Related problems