Home > Back-end >  Java Swing Wait
Java Swing Wait

Time:05-17

I am making a java code and I need to wait a few milliseconds.

while(true)
{
    //wait
    //more code
}

How can I make my code wait? I usually code in C# and i can do Thread.Sleep() but I didn’t found a way to make it work in java. Also, this is my current full code if you are wondering:

import javax.swing.*;
import java.util.*;

class Main{
    public static void main(String [] arg){
        Boolean isEnded = false;
        Scanner newScan = new Scanner(System.in);
        
        JFrame jf = new JFrame("Weird 3N 1 Calculator");
        JLabel jl = new JLabel("No Seed Entered.");
        
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        jf.setSize(300,300);
        jf.getContentPane().add(jl);
        jf.setVisible(true);

        System.out.println("Enter a seed: ");
        String seed = newScan.nextLine();
        Integer x = Integer.valueOf(seed);
        
        while(isEnded == false)         
        {
            //Thread.sleep(100);
            
            if(x == 1)  
            {
                isEnded = true;
                jl.setText("Last Number Is: "   x);
            }       
            else
            {
                if(x % 2 == 0)  
                {       
                    System.out.println(x / 2);
                    x = x / 2;
                    jl.setText("Now:"   x);
                }   
                else
                {   
                    System.out.println(x * 3   1);  
                    x = x * 3   1;
                    jl.setText("Now:"   x);
                }   
            }
        }
    }
}

Also, I just started coding in Java. My code is probably not well made and could be improved. Thanks

-Me

CodePudding user response:

The best way to wait here is Thread.sleep(n) method. In the situation, where you have multiple threads, you can tell threadA to wait treadB finished by calling treadB.join() method.

  • Related