线程休眠阻止我的Swing应用程序执行 [英] Thread sleep prevents my Swing application from executing

查看:85
本文介绍了线程休眠阻止我的Swing应用程序执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序发生了什么事情是有道理的,但我不知道如何解决它。以下是我的应用程序的简要说明:应在屏幕右下方显示一个计时器窗口并显示实时时间。一小时后,它应该做一些动作(我还没有决定行动)。我面临的问题是,在 Timer.java 中,当我刷新实时计时器的秒数时,我正在使用线程休眠,这阻止了我的所有应用程序继续执行,因此没有窗口正在显示。

What's is happening to my application makes sense but I don't know how to fix it. Here's a brief description of what my application does: A timer window should be display at the bottom right of my screen and show the live time. After an hour, it should do some action (I haven't decided the action yet). The problem I'm facing is that in Timer.java when I am refreshing the seconds for the live timer, I'm using thread sleep and this is preventing all my application to continue executing and therefor no window is showing.

这是我的代码,其中包含一些注释:

TimerFrame.java :应用程序的主框架

Here's my code with some comments:
TimerFrame.java: The main frame of the application

import java.awt.BorderLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;

import javax.swing.JFrame;

public class TimerFrame extends JFrame{
    public TimerFrame(String title) {
        // TItle and Layout
        super(title);
        setLayout(new BorderLayout());

        // Create the time panel and add it
        final TimerPanel tp = new TimerPanel();
        add(tp, BorderLayout.CENTER);

        // Timer is a class I've created, and it fires an event every second
        Timer time = new Timer();
        time.addTimeListener(new TimeListener() {
            public void refresh(String time) {
                tp.setText(time);
            }
        });

        // Configuration
        setSize(300,300);
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
        Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
        int x = (int) rect.getMaxX() - getWidth();
        int y = (int) rect.getMaxY() - getHeight();
        this.setLocation(x, y);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

TimePanel.java :应在屏幕上显示实时时间的面板

TimePanel.java: The panel that should display the live time on the screen

import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TimerPanel extends JPanel{

    private JLabel label;
    public TimerPanel() {
        label = new JLabel("Start Time");
        label.setFont(new Font("Arial",Font.BOLD,40));
        add(label);
    }

    public void setText(String text){
        label.setText(text);
    }
}

TimerListener.java :监听器接口

public interface TimeListener {
    public void refresh(String time);
}

Timer.java :给出实时时间,并且每秒都会触发一个名为刷新的事件。 在此calss中,thread.sleep()导致我的应用程序停止执行。

Timer.java: Gives the live time, and fires an event called refresh every second. In this calss, the thread.sleep() is causing my application to stop executing.

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Timer {
    private TimeListener sl = null;

    public Timer() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        boolean start = true;
        int StartHour = 0;
        while(true){
            try {
                // Get current time
                Calendar cal = Calendar.getInstance();

                // Initialize Start hour
                if(start){
                    StartHour = getHour(cal, sdf);
                    start = false;
                }

                // Fire event
                if(sl != null)
                    sl.refresh(sdf.format(cal.getTime()));

                // If one hour
                if(getHour(cal, sdf) - StartHour == 1){
                    // Code goes here

                    // Reset start
                    start = true;
                }

                // Delay 1 Sec
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Get Current Hour
     * @param cal Calentder
     * @param sdf Date format
     * @return Current Hour
     */
    public static int getHour(Calendar cal, SimpleDateFormat sdf){
        sdf.applyPattern("HH");
        int hour = Integer.parseInt(sdf.format(cal.getTime()));
        sdf.applyPattern("HH:mm:ss");
        return hour;
    }

    /**
     * Add Time Listener
     * @param sl TimeListener
     */
    public void addTimeListener(TimeListener sl){
        this.sl = sl;
    }
}

有没有人知道如何让我的应用程序执行一个会无限运行的thread.sleep()?谢谢:)

Does anyone know how to make my application execute while having a thread.sleep() that will run infinitely ? Thank you :)

推荐答案


有人知道如何在有线程的情况下执行我的应用程序。 sleep()

Does anyone know how to make my application execute while having a thread.sleep()

不要使用Thread.sleep()。

Don't use a Thread.sleep().

而是使用 Swing Timer 。您将Timer设置为每秒触发一次,以便更新组件。

Instead use a Swing Timer. You set the Timer to fire every second so you components can be updated.

这篇关于线程休眠阻止我的Swing应用程序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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