java - 如何使用计时器移动方 block

标签 java swing timer

我想移动我创建的正方形,但我不知道如何移动我绘制的所有正方形。到目前为止,我只移动我绘制的每个方 block ,因此,它会阻止我之前绘制的所有方 block 移动。我该如何解决这个问题。我想我必须使用存储方 block 的数组,但是我如何将它插入到计时器使用的 for 循环中?

package me;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.Timer;
import javax.swing.*;

public class Dots1panel extends JPanel
{
private static final long serialVersionUID = -7762339485544442517L;
private final int SIZE = 10;
private ArrayList<Point> pointList;
private int move;
private final int Delay=50,WIDTH=500, HEIGHT=400;
private int[] points  = new int[1000];
private int[] points2 = new int[1000];
Random count = new Random();
private Point point;
private Timer timer=null;
//  private int x, y;
//--------------------------------------------------------------------------        --------------------------------------------------------------------------------------------------------//
public Dots1panel()
{
    timer= new Timer(Delay, new ActListener());
    pointList = new ArrayList<Point>();
    //x =0;
    //y =50;
    setBackground (Color.GRAY);
    setPreferredSize (new Dimension(WIDTH, HEIGHT));
    addMouseListener (new DotsListener());
    for (move = 0; move < 1000; move++)
    {
        points[move] = count.nextInt(10) + 1;
        points2[move] = count.nextInt(10) + 1;
    }
    timer.start();
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    int R = (int) (Math.random( )*256); //randomizes colors
    int G = (int)(Math.random( )*256);
    int B= (int)(Math.random( )*256);
    Color randomColor = new Color(R, G, B);
    //randomize color of the rectangles//
    g.setColor(randomColor);
    {for (Point spot : pointList)
    g.fillRect (spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
    g.drawString ("Count: " + pointList.size(), 10, 15);}
 }
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
private class DotsListener implements MouseListener
{
    public void mousePressed(MouseEvent event)
    {
    pointList.add(event.getPoint());
    repaint();
    }
        public void mouseClicked (MouseEvent event) {}
        public void mouseReleased (MouseEvent event) {}
        public void mouseEntered (MouseEvent event) {}
        public void mouseExited (MouseEvent event) {}
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
 private class ActListener implements ActionListener
    {
    //-------------------------------------------------------------
    //  Updates the position of the image and possibly the direction
    //  of movement whenever the timer fires an action event.
    //-------------------------------------------------------------
            public void actionPerformed (ActionEvent event)
        {
            for(Point spot : pointList)
                point = spot;
            for(move = 0; move < pointList.size(); move++)
            {
            point.x += points[move];
            point.y += points2[move];

            if (point.x <= 0 || point.x >= WIDTH - SIZE)
                points[move]=points[move] * -1;
            if (point.y <= 0 || point.y >= HEIGHT - SIZE)
                points2[move]=points2[move] * -1;
            timer.restart();
            }
            repaint();
        }
    }
}

这是我的 Action 监听器

最佳答案

好吧,经过一番绞尽脑汁之后,我想我明白你想要做什么了。

基本上,在您的计时器中,您将每个运动 vector 应用于每个点,我怀疑这是否是您真正想要做的,相反,每个点应该有它自己的 vector 并且应该更新反对它

我简化了这个想法,创建了一个简单的可移动对象,它将当前位置和 vector 保持在一起,它还封装了运动和绘画,使其更加独立

public class MovableObject {

    private Point point;
    private Point vector;

    public MovableObject(Point point, Point vector) {
        this.point = point;
        this.vector = vector;
    }

    public void paint(Graphics2D g2d) {
        g2d.fillRect(point.x - SIZE, point.y - SIZE, SIZE * 2, SIZE * 2);
    }

    public void move(Dimension bounds) {
        point.x += vector.x;
        point.y += vector.y;
        if (point.x - SIZE <= 0) {
            vector.x *= -1;
            point.x = 0;
        } else if (point.x + SIZE > bounds.width) {
            vector.x *= -1;
            point.x = bounds.width - SIZE;
        }
        if (point.y - SIZE <= 0) {
            vector.y *= -1;
            point.y = 0;
        } else if (point.y + SIZE >= bounds.width) {
            vector.y *= -1;
            point.y = bounds.height - SIZE;
        }
    }

}

还有一个可运行的示例...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test extends JPanel {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new Test());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    private static final long serialVersionUID = -7762339485544442517L;
    private final int SIZE = 10;
    private ArrayList<MovableObject> pointList;
    private int move;
    private final int Delay = 50, WIDTH = 500, HEIGHT = 400;

    Random count = new Random();
    private Timer timer = null;
//--------------------------------------------------------------------------        --------------------------------------------------------------------------------------------------------//

    public Test() {
        timer = new Timer(Delay, new ActListener());
        pointList = new ArrayList<MovableObject>();
        //x =0;
        //y =50;
        setBackground(Color.GRAY);
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        addMouseListener(new DotsListener());
        timer.start();
    }
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        int R = (int) (Math.random() * 256); //randomizes colors
        int G = (int) (Math.random() * 256);
        int B = (int) (Math.random() * 256);
        Color randomColor = new Color(R, G, B);
        //randomize color of the rectangles//
        g2d.setColor(randomColor);
        for (MovableObject spot : pointList) {
            spot.paint(g2d);
        }
        g2d.drawString("Count: " + pointList.size(), 10, 15);
        g2d.dispose();
    }
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

    private class DotsListener implements MouseListener {

        public void mousePressed(MouseEvent event) {
        }

        public void mouseClicked(MouseEvent event) {
            pointList.add(new MovableObject(new Point(event.getPoint()), new Point(count.nextInt(10) + 1, count.nextInt(10) + 1)));
        }

        public void mouseReleased(MouseEvent event) {
        }

        public void mouseEntered(MouseEvent event) {
        }

        public void mouseExited(MouseEvent event) {
        }
    }
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

    private class ActListener implements ActionListener {
        //-------------------------------------------------------------
        //  Updates the position of the image and possibly the direction
        //  of movement whenever the timer fires an action event.
        //-------------------------------------------------------------

        public void actionPerformed(ActionEvent event) {
            for (MovableObject obj : pointList) {
                obj.move(getSize());
            }
            repaint();
        }
    }

    public class MovableObject {

        private Point point;
        private Point vector;

        public MovableObject(Point point, Point vector) {
            this.point = point;
            this.vector = vector;
        }

        public void paint(Graphics2D g2d) {
            g2d.fillRect(point.x - SIZE, point.y - SIZE, SIZE * 2, SIZE * 2);
        }

        public void move(Dimension bounds) {
            point.x += vector.x;
            point.y += vector.y;
            if (point.x - SIZE <= 0) {
                vector.x *= -1;
                point.x = 0;
            } else if (point.x + SIZE > bounds.width) {
                vector.x *= -1;
                point.x = bounds.width - SIZE;
            }
            if (point.y - SIZE <= 0) {
                vector.y *= -1;
                point.y = 0;
            } else if (point.y + SIZE >= bounds.width) {
                vector.y *= -1;
                point.y = bounds.height - SIZE;
            }
        }

    }
}

关于java - 如何使用计时器移动方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42124466/

相关文章:

Java:多维数组输出困惑?

java - 如何使 JFileChooser 仅显示具有某些特定名称 Java 的文件夹

java - 使用 JOGL 调整 GLJPanel 的大小会导致我的模型消失

c# - c++ 中是否存在来自 c# 的更准确的 Timers.Timer?

延迟调用函数的python装饰器

.net - 运行简单的计时器

java - Varargs 污染了堆

java swing 裁剪问题

java - JVM 在调用停止之前允许关闭 Hook 运行多长时间?

java - 有没有任何工具可以帮助我将 Java Swing 代码中的数据转换为模板文件?