2017-07-27 45 views
0

我希望Java中的数字时钟显示时间和日期,并且冒号应该闪烁。但是,我不能让冒号闪烁。这里是我的代码:使用ActionListener更新时钟 - Java

import java.awt.Font; 
import java.awt.Color; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.Timer; 
import javax.swing.SwingConstants; 
import java.util.*; 
import java.text.*; 

public class DigitalClock { 

    public static void main(String[] arguments) { 

    ClockLabel dateLable = new ClockLabel("date"); 
    ClockLabel timeLable = new ClockLabel("time"); 
    ClockLabel dayLable = new ClockLabel("day"); 

    JFrame.setDefaultLookAndFeelDecorated(true); 
    JFrame f = new JFrame("Digital Clock"); 
    f.setSize(300,150); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.setLayout(new GridLayout(3, 1)); 

    f.add(dateLable); 
    f.add(timeLable); 
    f.add(dayLable); 

    f.getContentPane().setBackground(Color.black); 

    f.setVisible(true); 
    } 
} 

class ClockLabel extends JLabel implements ActionListener { 
    String type; 
    SimpleDateFormat sdf; 
    public ClockLabel(String type) { 
    this.type = type; 
    setForeground(Color.green); 
    Calendar calendar = Calendar.getInstance(); 
    int seconds = calendar.get(Calendar.SECOND); 
    switch (type) { 
     case "date" : sdf = new SimpleDateFormat(" MMMM dd yyyy"); 
        setFont(new Font("sans-serif", Font.PLAIN, 12)); 
        setHorizontalAlignment(SwingConstants.LEFT); 
        break; 
     case "time" : if(seconds % 2 != 0) sdf = new SimpleDateFormat("hh:mm:ss a"); 
        else sdf = new SimpleDateFormat("hh mm ss a"); 
        setFont(new Font("sans-serif", Font.PLAIN, 40)); 
        setHorizontalAlignment(SwingConstants.CENTER); 
        break; 
     case "day" : sdf = new SimpleDateFormat("EEEE "); 
        setFont(new Font("sans-serif", Font.PLAIN, 16)); 
        setHorizontalAlignment(SwingConstants.RIGHT); 
        break; 
     default  : sdf = new SimpleDateFormat(); 
        break; 
    } 
    Timer t = new Timer(1000, this); 
    t.start(); 
    } 

    public void actionPerformed(ActionEvent ae) { 
     Date d = new Date(); 
    setText(sdf.format(d)); 
    } 
} 

正如你所看到的,我有以下行:

case "time" : if(seconds % 2 != 0) sdf = new SimpleDateFormat("hh:mm:ss a"); 
       else sdf = new SimpleDateFormat("hh mm ss a"); 

这样一来,冒号可见在秒数奇,否则冒号是不可见的。

问题是,如果我启动程序,第二个奇怪的时候,那么冒号总是可见的。我不明白为什么,因为第二次更改(时间更新),但冒号没有。

+1

您只在ClockLabel的构造函数中启动SimpleDateFormat一次。你应该在actionPerformed() – Johan

+0

中切换格式顺便说一句,这些日期时间类现在是传统的。签出java.time类,ThreeTen-Backport项目和ThreeTenABP项目。 –

回答

2

我认为你需要把这个检查

if(seconds % 2 != 0) 
    sdf = new SimpleDateFormat("hh:mm:ss a"); 
else 
    sdf = new SimpleDateFormat("hh mm ss a"); 

actionPerformed方法内。那就是你可以每秒切换的方式。

0

如果以调试模式运行项目,您将会明白switch-case语句只运行一次(启动时)。根据上面的实现,这是正常的,因为逻辑被放置在仅被称为树时间的构造函数中。

总之,您需要从根本上改变此实现。