简体   繁体   English

Java计时器动作监听器

[英]Java timer action listener

could use your help homework involving swing timers, action listeners and multiple objects. 可以使用您的帮助作业,其中包括摇摆计时器,动作侦听器和多个对象。 I don't know if posting the question is allowed here but i'm having trouble with the animation, here's what i have so far 我不知道是否可以在此处发布问题,但是我在动画方面遇到了麻烦,这是我到目前为止的问题

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. 创建一个具有两个双字段x和y的类Particle,创建一个将这些字段初始化为0到500之间的随机值的构造函数,返回其值的getX和getY方法,以及将void随机添加或减去一个的void move()方法x和y的每个值。 (The quantities added to x and y are two separate random numbers.) Next, create a class ParticleFieldWithTimer that extends JPanel. (添加到x和y的数量是两个独立的随机数。)接下来,创建一个扩展JPanel的类ParticleFieldWithTimer。 This class should prefer to be 500 * 500 pixels in size. 此类的大小应为500 * 500像素。 Its constructor should first fill an ArrayList field with 100 Particle objects, then start a Swing Timer that ticks 25 times a second. 它的构造函数应该首先用100个粒子对象填充ArrayList字段,然后启动一个摆动计时器,每秒滴答25次。 At each tick, the action listener should first call the method move for each particle, and then call repaint. 在每个滴答声处,动作侦听器应首先为每个粒子调用move方法,然后再调用repaint。 The paintComponent method of ParticleFieldWithTimer should draw each particle as a 3*3 rectangle to its current coordinates. ParticleFieldWithTimer的paintComponent方法应将每个粒子绘制为3 * 3矩形到其当前坐标。 Make sure that the Timer will stop when the user closes the frame 确保用户关闭框架时计时器停止

This is the ParticleFieldWithTimer class 这是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);
    }
}

This is the particle class 这是粒子类

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);
}

} }

This... 这个...

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();

        }
    });
}

Is the wrong approach, it is create a 100 Timer s, which will affect the performance of your system. 是错误的方法,它会创建一个100 Timer ,这会影响您的系统性能。

You are also creating a new Particle each time the timer ticks, which isn't what you really want to do either, you want to affect the Particle s you've already created... 每次计时器计时时,您还将创建一个新的Particle ,这也不是您真正想要做的,您想影响已经创建的Particle

Instead, create your particles... 相反,创建您的粒子...

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

Then create your Timer and within it, iterate through the particles you've already created... 然后创建您的Timer并在其中进行迭代,遍历您已经创建的粒子...

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

Don't forget to start the timer... 不要忘记启动计时器...

timer.start();

Or change the color of the Graphics context, which is probably still set to the background of the panel... 或更改Graphics上下文的颜色,它可能仍设置为面板的背景...

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

I also noted that... 我还注意到...

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

Isn't doing what you want. 没做你想做的。 It will always make the values between -1 and 1. Instead, you want to add the result to the x/y values... 它将始终使值在-1和1之间。相反,您想将结果添加到x / y值...

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

Now, this kind of made the values "drag" across the screen in a (mostly) uniform manner... 现在,这种方式使值(大多数)以统一的方式在屏幕上“拖动”。

You could try using... 您可以尝试使用...

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

But this ended up making them dance around in place (mostly)... 但这最终使他们在原地跳舞(大部分)...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM