我正在尝试编写一个每秒绘制一个新正方形的程序。这是我的 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/