Question: For this lab, you'll build on the Dots.java and DotsPanel.java programs. Instead of drawing dots you will draw squares so add that change. Add animation

For this lab, you'll build on the Dots.java and DotsPanel.java programs.

Instead of drawing dots you will draw squares so add that change.

Add animation using a Timer so that the squares all move when drawn. Make each square move at random speed (in x and y directions), and have the squares "bounce" appropriately off all four sides of the screen.

HINTS:

Create 2 arrays of size 1000 to hold random values between 1 and 10 for the X movements and Y movements. This will allow your rectangles to have independent movement speeds.

You will need to create a ActionListener class similar to what is used in ReboundPanel class.

Inside the Actionistener class you create you will want to reference the X and Y array indexes rather than the static moveX and moveY used in the ReboundPanel.

Dots.java Code:

import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.security.SecureRandom; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel;

public class Dots extends JPanel { private final int SIZE = 6; private ArrayList pointList; public Dots() { pointList = new ArrayList(); addMouseMotionListener(new DotsListener()); setBackground(Color.black); setPreferredSize(new Dimension(300, 200)); } private void setColor(Color color) { } public void paint(Graphics page) { super.paintComponent(page); SecureRandom randomNum = new SecureRandom(); Color color = new Color(randomNum.nextInt(256), randomNum.nextInt(256), randomNum.nextInt(256)); page.setColor(color); for (Point spot : pointList) page.fillOval(spot.x - SIZE, spot.y - SIZE, SIZE * 2, SIZE * 2); page.drawString("Count: " + pointList.size(), 5, 15); } private class DotsListener implements MouseMotionListener { public void mousePressed(MouseEvent event) { pointList.add(event.getPoint()); repaint(); } public void mouseMoved(MouseEvent event) { } public void mouseClicked(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mouseDragged(MouseEvent event) { pointList.add(event.getPoint()); repaint(); } } public static void main(String args[]) { JFrame frame = new JFrame(); frame.add(new Dots()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(20,20, 500,500); frame.setVisible(true); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!