定时器不喜欢压倒一切

Timer doesn't feel like overriding

我的一个朋友给了我这个计时器代码。我必须说我是初学者,所以我不明白@Override是什么,但是代码对其他朋友有效。

Eclipse 说 public 空行:

Multiple markers at this line:

  • The method actionPerformed(ActionEvent) of type new ActionListener(){} must override a superclass method
  • implements java.awt.event.ActionListener.actionPerformed

密码是:

 final Timer t = new Timer(tijd, new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        lx = lx-s1;
    }
});
t.start();

随之而来的是删除 @Override 的建议,但由于我不确定它的作用,我不知道我是否会删除代码中的重要内容。我想它不在那里是因为有人认为包含代码会很有趣。

所以我的问题是: 1.如何移动标签? 2.@Override有什么问题?

您在这里所做的是当场创建 ActionListener 接口的匿名实现,并将其作为 Timer 构造函数 Timer(int x, ActionListener y) 的第二个参数直接传递。 此接口的任何实现都必须提供方法 ActionPerformed (ActionEvent e) 的实现,因此您可以就地提供它。从 Java 6 开始,接口方法的实现必须使用 @Override 标记进行注释。如果您使用的是 Java 5,则它是可选的。 您可以使用命名的(非匿名的)class:

像这样编写代码
static class LabelMover implements ActionListener {
  @Override
  public void actionPerformed(ActionEvent e) {
  ...
  }
}

Timer timer = new Timer (tijd, new LabelMover());

这会导致相同的行为。 然而,问题是:您在这里使用的是哪个定时器 class? Java 计时器 class (java.util.Timer) 没有将 ActionListener 作为第二个参数的构造函数。 如果你想让标签每隔这么多毫秒递增移动,那么你应该创建一个 TimerTask 来执行此操作,然后创建一个 Timer 并使用该计时器安排 TimerTask:

static class LabelMover implements TimerTask {
    @Override
    public void run() {
    // code to move the label
    }
}
Timer timer = new Timer();
timer.schedule(new TimerTask(), 0, tijd);

好吧,在这种情况下,@Override 确实可以忽略不计。然而,移动标签的代码非常重要。 你应该以此为基础:

在计时器的动作侦听器中执行如下操作:x = x - 1; 然后 Label.setLocation(x,y);

这应该可以解决问题![​​=10=]