移动对象和定时器移动对象和定时器(Moving objects and timers)

2019-05-09 01:27发布

我有一个屏幕,说500的宽度和高度400,以及我有一串形状的向量。 让说向量具有例如2种不同的形状。 我希望对象随机从屏幕底部弹出达到一定的上升和下降,然后回落(类似于游戏水果忍者,这里的水果都是我的形状)。

在我的主要(视图)我具有形状,其中我实例定时器的载体,添加到阵列和使用所述翻译功能将它们放置在屏幕的BUTTOM。 我的计时器发生在动作监听器基本上改变了翻译的形状向上移动,直到上升,然后下降,但我的问题是,所有的形状在同一时间启动不管。

事情是这样的:

        Shape f = new Shape(new Area(new Ellipse2D.Double(0, 50, 50, 50)));   
        f.translate(0, 400);   
        f.timer = new Timer( 10 , taskPerformer);    
        f.timer.start();    
        vector.add(f);    


        Shape f2 = new Shape(new Area(new Rectangle2D.Double(0, 50, 50, 50)));    
        f2.translate(200, 400);    
        f2.timer = new Timer( 10 , taskPerformer);    
        f2.timer.setInitialDelay(5000);    
        f2.timer.start();    
        vector.add(f2);

和我的动作侦听器:

        Random generator = new Random();            
        ActionListener taskPerformer = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                   //...Perform a task...
             for (Shape s : model.getShapes()) {
                // Scale object using translate
                // once reached ascent drop down
                // translate to diffrenet part of the bottom of the screen
                // delay its timer
                }    
                update();
                //basically repaints      
            }

    };

我运行到所有的形状遵循相同的计时器,并开始在同一时间(无延迟)将弹出问题...

任何建议如何避免这个问题,或者是有不同的方法,我应该尝试

Answer 1:

“我希望对象随机从屏幕底部弹出达到一定的上升和下降,然后背下来”

请参见下面的可运行的例子。 我要做的就是通过一个radomDelayedStartShape 。 计时器每打勾, randomDelayedStart降低直到它达到0,这时候要绘制的国旗在升起。 大部分逻辑是在Shape类方法,其被称为在Timer小号Actionlistener 。 一切都在一个Timer 。 对于上升,我只是用一个硬编码的50,但你也可以通过随机上升到了Shape 。 让我知道如果您有任何问题。 我试图使代码尽可能明确。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class RandomShape extends JPanel {

    private static final int D_HEIGHT = 500;
    private static final int D_WIDTH = 400;
    private static final int INCREMENT = 8;
    private List<Shape> shapes;
    private List<Color> colors;
    private Timer timer = null;

    public RandomShape() {
        colors = createColorList();
        shapes = createShapeList();

        timer = new Timer(30, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for (Shape shape : shapes) {
                    shape.move();
                    shape.decreaseDelay();
                    repaint();
                }
            }
        });
        JButton start = new JButton("Start");
        start.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                timer.start();
            }
        });
        JButton reset = new JButton("Reset");
        reset.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                shapes = createShapeList();
                timer.restart();
            }
        });

        JPanel panel = new JPanel();
        panel.add(start);
        panel.add(reset);
        setLayout(new BorderLayout());
        add(panel, BorderLayout.PAGE_START);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Shape shape : shapes) {
            shape.drawShape(g);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(D_WIDTH, D_HEIGHT);
    }

    private List<Color> createColorList() {
        List<Color> list = new ArrayList<>();
        list.add(Color.BLUE);
        list.add(Color.GREEN);
        list.add(Color.ORANGE);
        list.add(Color.MAGENTA);
        list.add(Color.CYAN);
        list.add(Color.PINK);
        return list;
    }

    private List<Shape> createShapeList() {
        List<Shape> list = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            int randXLoc = random.nextInt(D_WIDTH);
            int randomDelayedStart = random.nextInt(100);
            int colorIndex = random.nextInt(colors.size());
            Color color = colors.get(colorIndex);
            list.add(new Shape(randXLoc, randomDelayedStart, color));
        }

        return list;
    }

    class Shape {

        int randXLoc;
        int y = D_HEIGHT;
        int randomDelayedStart;
        boolean draw = false;
        boolean down = false;
        Color color;

        public Shape(int randXLoc, int randomDelayedStart, Color color) {
            this.randXLoc = randXLoc;
            this.randomDelayedStart = randomDelayedStart;
            this.color = color;
        }

        public void drawShape(Graphics g) {
            if (draw) {
                g.setColor(color);
                g.fillOval(randXLoc, y, 30, 30);
            }
        }

        public void move() {
            if (draw) {
                if (y <= 50) {
                    down = true;
                }

                if (down) {
                    y += INCREMENT;
                } else {
                    y -= INCREMENT;
                }
            }
        }

        public void decreaseDelay() {
            if (randomDelayedStart <= 0) {
                draw = true;
            } else {
                randomDelayedStart -= 1;
            }
        }

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new RandomShape());
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}


文章来源: Moving objects and timers