Java - 将Timer代码放在我的文件中的位置?

时间:2015-10-09 05:49:15

标签: java user-interface clock

假设我有一个适用于时钟的GUI的以下框架(我可能导入的内容超出了我的需要;我是从一个更大的文件中创建的):

import java.util.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.Timer;

public class clock extends JFrame implements ActionListener
{
    Container c;
    JLabel year, month, date, hour, minute, second;

    public clock(Calendar cal)
    {
        //set up GUI; initialize and add all 6 JLabels
    }

    public static void main(String args[])
    {
        Calendar current = Calendar.getInstance();
        clock c = new clock(current);
    }
}

我希望每秒更新时钟。据我所知,这至少是我需要的代码的一部分:

ActionListener listener = new ActionListener()
{
    public void actionPerformed(ActionEvent event)
    {
        cal.
        year.setText("year: " +cal.get(Calendar.YEAR));
        month.setText("month: " +cal.get(Calendar.MONTH));
        date.setText("date: " +cal.get(Calendar.DATE));
        hour.setText("hour: " +cal.get(Calendar.HOUR));
        minute.setText("minute: " +cal.get(Calendar.MINUTE));
        second.setText("second: " +cal.get(Calendar.SECOND));
    }
};

Timer timer = new Timer(500, listener);
timer.setInitialDelay(0);
timer.start();

第二个代码块是在构造函数中,还是在构造函数和main之外?我已经尝试了两种方法,每种方法都有不同的错误。我已经阅读了有关需要 @Override 才能使用的内容,但我对此并不熟悉。此外,这是我的计时器工作所需的所有代码,还是有更多(如果是,那是什么)?我在这里看到一个时钟的例子基本上完成了我正在尝试做的事情,但是它使用了我从未被教过的各种其他东西( runnable 尝试捕捉等等),所以如果可能的话,我想用我所知道的做。

我意识到,如果该代码块超出了构造函数的范围,我可能需要让我的Calendar对象全局为ActionListener访问它。

编辑:我更新了actionPerformed方法以包含日历的更新。我还提供了我得到的错误(请注意,行号不正确,因为我的实际构造函数包含的行数多于此处的骨架数量):

当我将第二个代码块放在构造函数中时:

clock.java:10: error: clock is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener
public class clock extends JFrame implements ActionListener
       ^

当我将第二个代码块放在构造函数之外时:

clock.java:59: error: <identifier> expected
    timer.setInitialDelay(0);
                         ^
clock.java:59: error: illegal start of type
    timer.setInitialDelay(0);
                          ^
clock.java:60: error: <identifier> expected
    timer.start();
               ^

EDIT2:以下是我从MadProgrammer的解决方案中得到的例外情况:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Clock$1.actionPerformed(clock.java:18)
    at javax.swing.Timer.fireActionPerformed(Timer.java:313)
    at javax.swing.Timer$DoPostEvent.run(Timer.java:245)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

EDIT3:@ MadProgrammer的更新解决方案出错:

Clock.java:33: error: cannot find symbol
        setLayout(new FlowLayout());  
                  ^
  symbol:   class FlowLayout
  location: class Clock

1 个答案:

答案 0 :(得分:1)

此...

clock.java:59: error: <identifier> expected
    timer.setInitialDelay(0);
                         ^
clock.java:59: error: illegal start of type
    timer.setInitialDelay(0);
                          ^
clock.java:60: error: <identifier> expected
    timer.start();

表示您正在导入错误的Timer。 Java有两个,java.util.Timerjavax.swing.Timer,这是你想要的。

通常情况下,我不会因为这个原因而使用通配符导入,但我的IDE的自动导入功能也会使用绝对导入。

但你可以使用

import javax.swing.Timer;

或使用绝对声明,如...

javax.swing.Timer timer = new javax.swing.Timer(500, listener);

取决于您的需求(使用java.util.Datejava.sql.Date时,您经常会在此处结束:P)

此...

clock.java:10: error: clock is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener
public class clock extends JFrame implements ActionListener

表示您尚未实施ActionListener接口合同的要求。在你的情况下,我不认为你真的需要它,因为你在内部制作自己的ActionListener

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Clock extends JFrame {

    JLabel year, month, date, hour, minute, second;

    public Clock(Calendar cal) {
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                cal.setTime(new Date());
                updateTime(cal);
            }
        };

        year = new JLabel();
        month = new JLabel();
        date = new JLabel();
        hour = new JLabel();
        minute = new JLabel();
        second = new JLabel();

        setLayout(new FlowLayout());

        add(year);
        add(month);
        add(date);
        add(hour);
        add(minute);
        add(second);

        updateTime(cal);

        javax.swing.Timer timer = new javax.swing.Timer(500, listener);
        timer.setInitialDelay(0);
        timer.start();
    }

    protected void updateTime(Calendar cal) {
        year.setText("year: " + cal.get(Calendar.YEAR));
        month.setText("month: " + cal.get(Calendar.MONTH));
        date.setText("date: " + cal.get(Calendar.DATE));
        hour.setText("hour: " + cal.get(Calendar.HOUR));
        minute.setText("minute: " + cal.get(Calendar.MINUTE));
        second.setText("second: " + cal.get(Calendar.SECOND));
    }

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

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

                Calendar current = Calendar.getInstance();
                Clock frame = new Clock(current);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}