【问题标题】:Using an anonymous listener object inside the Timer class在 Timer 类中使用匿名侦听器对象
【发布时间】:2015-05-03 06:39:08
【问题描述】:

可以吗?我试过这样做,但它给出了编译错误:

Timer t = new Timer(1000,new ActionListener() {
    public void actionPerformed(ActionEvent event) {

    }
});

这是完整的代码供参考


完整代码:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class Scratch {


    public static void main(String[] args) {
        JFrame frame = new JFrame("Moving Rectangle");
        frame.setSize(1000,700);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;

            }

        });
        Timer t = new Timer(1000,new ActionListener() {
            public void actionPerformed(ActionEvent event) {

            }
        });

    }
}

我需要输入一些内容,因为我的问题主要是代码。

【问题讨论】:

  • 编译错误是什么?
  • 是的,它可以很简单地完成,你几乎明白了!
  • 表示构造函数未定义。 :(
  • It says that the constructor is undefined - 对我来说毫无意义,因为我复制并粘贴了代码并且编译得很好。发布一个正确的SSCCE 来证明问题。您可能还有其他问题,可能是缺少导入语句。所以基本上创建一个 main() 方法并将代码添加到方法中并开始编译。
  • 好的,这是我的全部代码:

标签: java


【解决方案1】:

但它给出了编译错误:

当您提出问题时,请发布错误,这样我们就不必猜测了。

当我将您的代码添加到一个空的 main() 方法时,我得到了以下信息,因为我在测试类中有很多标准的导入语句:

Main.java:21: error: reference to Timer is ambiguous, both class java.util.Timer in java.util and class javax.swing.Timer in javax.swing match
Timer t = new Timer(1000, new ActionListener()

解决方案可以使用:

javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener()

避免混淆。

编辑:

您看过我上面的解决方案了吗?注意我是如何使用 javax.swing.Timer 的?

import java.util.Timer;

不要使用 java.util.Timer。使用 Swing,您需要使用 Swing Timer,因此代码在 EDT 上执行。

改为使用:

import javax.swing.Timer;

【讨论】:

  • 对不起,实际的错误是它说构造函数是未定义的。 :(
  • @KaneWilliamson,查看编辑。这就是我们需要SSCCE 的原因。了解代码的上下文和编译器消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
相关资源
最近更新 更多