java - 如何使用 Swing 定时器?

标签 java swing timer actionlistener

我正在尝试编写一个每秒绘制一个新正方形的程序。这是我的 JPannel 类的代码。我还有另外两个类(class),但我相信它们与我的问题无关。一个有 main 方法,它创建另一个包含 JFrame 的类的对象。我只是不知道如何让计时器工作以及它是如何工作的。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Drawing extends JPanel  implements ActionListener{
    Drawing(){
        super();
        setBackground(Color.WHITE);
        startTimer();        
    }

    public void startTimer() {
           Timer timer = new Timer(1000, this);
           timer.start();
    }

    public void paintComponent(Graphics g) {
         int width = getWidth();             
         int height = getHeight();         

         super.paintComponent(g);  
         g.setColor(Color.BLUE);

         for(int x = 0; x < 999; x ++) {
         for(int y = 0; y < 999; y ++) {

                 g.drawRect(0,0, x, y);


         }
         }

    }

    public void actionPerformed(ActionEvent e) { 
           repaint();
    }

}

最佳答案

摆脱 paintComponent 方法中的 for 循环。请注意,绘画方法不应更改对象状态。相反,计时器的 actionPerformed 方法会被重复调用 - 在那里推进你的计数器或 x/y 变量,然后调用 repaint()

例如,

private int x;
private int y;

public void paintComponent(Graphics g) {
     super.paintComponent(g);  
     g.setColor(Color.BLUE);


     // RECT_WIDTH etc are constants
     g.drawRect(x, y, RECT_WIDTH, RECT_HEIGHT);
}


public void actionPerformed(ActionEvent e) { 
    int width = getWidth();             
    int height = getHeight();

    // code here to change the object's state -- here to change
    // location of the rectangle
    x++;
    y++;

    // TODO: check that x and y are not beyond bounds and if so,
    // then re-position them

    repaint();
}

关于java - 如何使用 Swing 定时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428562/

相关文章:

java - 升级到 Apache Cayenne 4.0 Milestone 5 版本后出现错误

java - JTabbedPane 问题 : how to find and track existing JTabbedPane's tab

每次计时器刷新后,C# 列表框选择的索引重置为 0

actionscript-3 - Flex播放一系列声音文件

java - 错误 ValidationException : Call to TraversableResolver. isReachable() 引发异常

java - 数据表-限制输出

java - 按钮中的 Activity

java - 如何将文本文件中的ArrayList填充到JCombobox

java - 一个类的方法没有被另一个类调用

java - 使用 Spring 引导在 Intellij 中实时加载 Assets