可以做到吗?我尝试这样做,但它给出了编译错误:
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) {
}
});
}
}
我需要输入一些东西,因为我的问题主要是代码。
但它给出了一个编译错误:
当您提出问题时,请发布错误,这样我们就不必猜测了。
当我将您的代码添加到空的 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 计时器,因此代码在 EDT 上执行。
而是使用:
import javax.swing.Timer;