[英]How to use swing timer?
I'm trying to write a program that draws a new square every second. 我正在尝试编写一个每秒绘制一个新方块的程序。 This is my code for my JPannel class.
这是我的JPannel类的代码。 I have two other classes but I beleive they are irrelivant to my question.
我有另外两个班级,但我相信他们对我的问题不感兴趣。 One has the main method where it creates an object of the other class that contains the JFrame.
一个有main方法,它创建包含JFrame的另一个类的对象。 I just cant figure out how to get the timer to work and how it works.
我只是想弄清楚如何让计时器工作以及它是如何工作的。
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();
}
}
Get rid of the for loops in your paintComponent method. 摆脱paintComponent方法中的for循环。 Note that painting methods should not change object state.
请注意,绘制方法不应更改对象状态。 Instead the timer's actionPerformed method gets repeatedly called -- advance your counter or x/y variables there, and then call
repaint()
. 而是重复调用计时器的actionPerformed方法 - 在那里推进你的计数器或x / y变量,然后调用
repaint()
。
eg, 例如,
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.