简体   繁体   English

Java Swing 等待

[英]Java Swing Wait

I am making a java code and I need to wait a few milliseconds.我正在制作一个 java 代码,我需要等待几毫秒。

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.我通常用 C# 编写代码,我可以做Thread.Sleep()但我没有找到让它在 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.另外,我刚开始用 Java 编码。 My code is probably not well made and could be improved.我的代码可能做得不好,可以改进。 Thanks谢谢

-Me -我

The best way to wait here is Thread.sleep(n) method.在这里等待的最好方法是Thread.sleep(n)方法。 In the situation, where you have multiple threads, you can tell threadA to wait treadB finished by calling treadB.join() method.在有多个线程的情况下,您可以通过调用treadB.join()方法告诉threadA等待treadB完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM