Java 定时器 Action 监听器

标签 java swing timer paintcomponent

可以使用你的帮助家庭作业,涉及 Swing 计时器、 Action 监听器和多个对象。我不知道是否允许在这里发布问题,但我在动画方面遇到了问题,这是我目前所拥有的

Create a class Particle that has two double fields x and y, a constructor that initializes these fields to random values between 0 and 500, methods getX and getY that return their values, and a method void move() that randomly adds or subtracts one to each of the values of x and y. (The quantities added to x and y are two separate random numbers.) Next, create a class ParticleFieldWithTimer that extends JPanel. This class should prefer to be 500 * 500 pixels in size. Its constructor should first fill an ArrayList field with 100 Particle objects, then start a Swing Timer that ticks 25 times a second. At each tick, the action listener should first call the method move for each particle, and then call repaint. The paintComponent method of ParticleFieldWithTimer should draw each particle as a 3*3 rectangle to its current coordinates. Make sure that the Timer will stop when the user closes the frame

这是 ParticleFieldWithTimer 类

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;


public class ParticleFieldWithTimer extends JPanel{
    private ArrayList<Particle> particle = new ArrayList<Particle>();
    Timer timer; 
    boolean b; 
    public ParticleFieldWithTimer (){
        this.setPreferredSize(new Dimension(500,500));


    for(int i = 0; i < 100; i++) { 
        particle.add(new Particle());
        timer = new Timer(40, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                // change polygon data
                // ...
                Particle p = new Particle();
                p.move();
                repaint();

            }
        });


    }





}
   public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        for (Particle p: particle) {

        double temp1 = p.getX();
        double temp2 = p.getX();
        int tempX = (int) temp1;
        int tempY = (int) temp2;
        g2.fillRect(tempX, tempY, 3, 3);
        }




    }
   public static void main(String[] args) {
        final JFrame f = new JFrame("ParticleField");
        final ParticleFieldWithTimer bb = new ParticleFieldWithTimer();
        f.setLayout(new FlowLayout());
        f.add(bb);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                try {
                    bb.finalize();
                } catch (Throwable e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                f.dispose();
            }
        });
        f.pack();
        f.setVisible(true);
    }
}

这是粒子类

import java.util.Random;


public class Particle {
private double x , y ;

Random r = new Random();
public Particle () {

    x = r.nextDouble()*500;
    y = r.nextDouble()*500;

}
public Double getX() {
    return x;
}
public Double getY() {
    return y;
}
public void move() {

    x = r.nextInt(2) - 1;
    y = r.nextInt(2) - 1;
    System.out.println(x + "  " + y);
}

最佳答案

这...

for(int i = 0; i < 100; i++) { 
    particle.add(new Particle());
    timer = new Timer(40, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            // change polygon data
            // ...
            Particle p = new Particle();
            p.move();
            repaint();

        }
    });
}

是错误的做法,它是创建一个100个Timer,这会影响你系统的性能。

每次计时器滴答时,您还创建了一个新的 Particle,这也不是您真正想要做的,您想要影响 Particle已经创建...

相反,创建您的粒子...

for(int i = 0; i < 100; i++) { 
    particle.add(new Particle());
}

然后创建您的 Timer 并在其中迭代您已经创建的粒子...

timer = new Timer(40, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        for (Particle p : particle) {
            p.move();
        }
        repaint();
    }
});

不要忘记启动计时器...

timer.start();

或者更改 Graphics 上下文的颜色,它可能仍然设置为面板的背景......

Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
for (Particle p : particle) {

我还注意到...

x = r.nextInt(2) - 1;
y = r.nextInt(2) - 1;

没有按照您的意愿行事。它总是使值介于 -1 和 1 之间。相反,您想将结果添加到 x/y 值...

x += r.nextInt(2) - 1;
y += r.nextInt(2) - 1;

现在,这种方式使值以(大部分)统一的方式“拖”过屏幕......

你可以尝试使用...

x += r.nextBoolean() ? 1 : - 1;
y += r.nextBoolean() ? 1 : - 1;

但这最终让他们原地跳舞(大部分)......

关于Java 定时器 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22366890/

相关文章:

java - 在同一个 jScrollPane 中制作两个表

java - 如何在空闲时自动注销?

javascript - 在 JS 中创建 "delay"函数?

java - 直接访问嵌入式缓存 HSQLDB 服务器?

java - 如何在 Java 中解析或拆分 URL 地址?

java - 微调器无法保存所选值

linux - Linux 中的多个硬件定时器

java - Android:哪个运算符用于模数(%不适用于负数)

java - 从 JFrame 引用 JPanel 组件

actionscript-3 - TimerEvent 与 AS3/Flex 游戏中的 ENTER_FRAME?