简体   繁体   English

JLabel不使用计时器更新

[英]JLabel not updating with timer

I have searched all over the internet trying to find how to make an automatic updating clock gui program with no luck. 我在整个互联网上进行搜索,试图找到如何制作自动更新时钟GUI程序的过程,但是没有运气。 I have tried many different methods, ending with the same results. 我尝试了许多不同的方法,最终得到了相同的结果。 I am using the swing Timer as I have read that's the best way to deal with gui's. 正如我所读到的,我正在使用Swing Timer,这是处理gui的最佳方法。 I have tried validate(), revalidate(), repaint(). 我已经尝试了validate(),revalidate(),repaint()。 Here is part of the code: 这是代码的一部分:

import javax.swing.*;
//import java.awt.event.*;
import java.util.*;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ClockPanel extends JPanel { 
    Calendar now = Calendar.getInstance();
    int hour = now.get(Calendar.HOUR_OF_DAY);
    int minute = now.get(Calendar.MINUTE); 
    int second = now.get(Calendar.SECOND);
    int month = now.get(Calendar.MONTH) + 1;
    int day = now.get(Calendar.DAY_OF_MONTH);
    int year = now.get(Calendar.YEAR);

    private String currentTime;
    private JLabel current;

    public ClockPanel() {
        super();
        currentTime = getTime();
        current = new JLabel(currentTime);
        add(current);

        ActionListener updater = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                getTime();
                if(second == 60){
                    current.setText(currentTime);
                    revalidate();

                }
                getTime();
            }
        };
        Timer timer = new Timer(1000, updater);
        timer.start();
    }

This is the final code that I have ended up with; 这是我最终得到的最终代码; I know it's wrong, but I have changed it so much for hours that I gave up. 我知道这是错误的,但是我已经放弃了好几个小时才进行了很大的更改。 Thanks 谢谢

EDIT: Here's the rest of the code 编辑:这是其余的代码

public String getTime() {
        String time;
        String period = "AM";
        String monthName = "";
        switch(month) {
            case (1):
                monthName = "January";
                break;
            case (2):
                monthName = "February";
                break;
            case (3):
                monthName = "March";
                break;
            case (4):
                monthName = "April";
                break;
            case (5):
                monthName = "May";
                break;
            case (6):
                monthName = "June";
                break;
            case (7):
                monthName = "July";
                break;
            case (8):
                monthName = "August";
                break;
            case (9):
                monthName = "September";
                break;
            case (10):
                monthName = "October";
                break;
            case (11):
                monthName = "November";
                break;
            case (12):
                monthName = "December";
                break;
        }
        if(hour >= 12){
            period = "PM";
        }
        time = monthName + " " + day + ", " + year + " "
                + hourCheck(hour) + ":" + minuteCheck(minute) + period;
        return time;
    }

    private int hourCheck(int hour) {
        if(hour > 12){
            hour -= 12;
            return hour;
        }
       if(hour == 0) {
            hour += 12;
            return hour;
        }
       return hour;
    }

    private StringBuilder minuteCheck(int minute) { 
       StringBuilder time = new StringBuilder();

       if(minute < 10) {
           return time.append("0").append(minute);
       }
       else {
           time.append("").append(minute);
       }
       return time;
    }

}

You're calling getTime() , but ignoring what it returns. 您正在调用getTime() ,但忽略它返回的内容。 The current time thus stays as it was before. 因此,当前时间保持不变。 Replace your code with: 将代码替换为:

    ActionListener updater = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            String newTime = getTime();
            current.setText(newTime);
        }
    };

EDIT : 编辑:

Not only do you ignore the value returned by getTime() , but getTime() also always returns the same thing, since you're always reuse the month, minute, seconds, etc. that have been initialized only once, when the panel has been constructed. 您不仅会忽略getTime()返回的值,而且getTime()还会始终返回相同的结果,因为当面板显示时,您总是重复使用仅初始化一次的月份,分钟,秒数等。被建造。 You're also making your life really difficult by not using the standard DateFormat class. 通过不使用标准的DateFormat类,也使生活变得非常困难。

Remove ALL the fields from your panel except the JLabel, and change the getTime() method to something like this: 从面板中除去JLabel之外的所有字段,然后将getTime()方法更改为如下所示:

private String getTime() {
    // get the CURRENT date:
    Date currentDate = new Date();

    // format it and return it:
    return new SimpleDateFormat("MMMM dd, yyyy hh:mm a").format(currentDate);
}

You could adjust your code to this and it will work: 您可以对此进行调整,它将起作用:

public class ClockPanel extends JPanel { 
    private final JLabel current;

    public ClockPanel() {
        current = new JLabel(now());
        add(current);

        new Timer (1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                current.setText(now());
            }
        }).start();
    }

    private static String now() {
        // implement your own
        return new Date().toString();
    }

    public static void main(String[] args) {
        JFrame main = new JFrame("Simple Clock");
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.setSize(200, 200);
        main.setContentPane(new ClockPanel());
        main.setVisible(true);
    }
}

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

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