Java Sleep 无法循环工作 [英] Java Sleep not working in loop

查看:50
本文介绍了Java Sleep 无法循环工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 java 程序中做的是,当我按下按钮时,它会每隔一段时间在 textfield 中显示文本.即我按下按钮,然后一个 jFrame 弹出,有一个标签显示如下文本:第一秒:第一"然后是 1 秒的时间延迟然后第二件事:第二"

What I want to do in my java program is, that when I press the button it displays text in textfield in intervals of time. i.e I press the button then a jFrame pops up and there is a label which shows text like: 1st second:"1st" then a time lag of say 1 sec then 2nd thing: "2nd"

我是新手,我尝试在 Google 上搜索此问题,但即使在 3-4 小时后也找不到解决方案我尝试了很多东西:睡觉,尝试捕捉...

I am a newbie and I tried to Google this problem but I couldn't find a solution even after 3-4 hours I tried a lot of things: sleep, try n catch...

请把答案写得非常简单.

Please write the answer very simplified.

这是我的代码:在下面的代码中,当按下按钮时,jFrame 出现但里面有一个白色的屏幕,当总和结束时,它的屏幕变成灰色并显示答案....

Here is my code: In the following code, when the button is pressed, the jFrame comes but has a white screen in it and when the sum ends, its screen turns grey and it shows the answer....

   private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    See.setVisible(true);//See is the JFrame   
    t007.setVisible(true);//Label in See
    l2.setVisible(true);//TextField in See
    int ran, g, d, col, ran2;
    double y = 1000 * (Double.parseDouble(t2.getText()));
    int x = (int) y;
    d = 0;
    double c = Math.pow(10, Integer.parseInt(t1.getText()));
    col = Integer.parseInt(t3.getText());
    for (g = 0; g < col;) {
        ran = (int) (Math.random() * (c)); // Random Number Creation Starts
        if (ran > (c / 10)) {
            g = g + 1;
            ran2 = ((int) (Math.random() * 10)) % 2;
            if (ran2 == 1) {
                ran = ran * (-1);
            }
            d = d + ran;
            if (d < 0) {
                ran = ran * (-1);
                d = d + (2 * ran);
            }
            l2.setVisible(true);
            t007.setText("" + ran);
            System.out.println("" + ran);
            jButton6.doClick();
            //Pausing (Sleep)
            try {
                  Thread.sleep(x);

             } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            }
            }
            }
             l2.setText("" + d);
               }                                        

推荐答案

Swing 是一个单线程框架,也就是说,对 UI 的所有交互和修改都应该在事件调度线程的上下文中发生.

Swing is a single threaded framework, that is, all interactions and modifications to the UI are expected to occur within the context of the Event Dispatching Thread.

EDT 负责处理重绘请求等.

The EDT is responsible for, amongst other things, processing repaint requests.

任何阻止 EDT 运行的东西(如 Thread.sleep 和长时间循环)都将阻止它处理事件,实际上挂起"您的应用程序直到它变得畅通无阻......

Anything that stops the EDT from running (like Thread.sleep and looping for a long time) will prevent it from processing the events, virtually "hanging" your application until it becomes unblocked...

现在,我试图破译你的程序试图做什么......但失败了,所以相反......我做了一个漂亮的计数器......

Now, I tried to decipher what you program was trying to do...but failed, so instead...I made a pretty counter...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TickOver {

    public static void main(String[] args) {
        new TickOver();
    }

    public TickOver() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextField field;
        private JButton button;
        private int tick; 
        private Timer timer;

        public TestPane() {

            field = new JTextField(10);
            field.setEditable(false);
            button = new JButton("Start");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    button.setEnabled(false);
                    tick = 0;
                    timer.start();
                }
            });

            timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    field.setText(Integer.toString(++tick));
                    if (tick > 4) {
                        timer.stop();
                        button.setEnabled(true);
                    }
                }
            });
            timer.setInitialDelay(0);

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(field, gbc);
            add(button, gbc);

        }
    }
}

仔细查看 Swing 中的并发 以了解更多详细信息...

Take a close look at Concurrency in Swing for more details...

这篇关于Java Sleep 无法循环工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆