Problem:
Create a GUI java-based application that animates the
collision of two rockets.
collision of two rockets.
Output:
Solution:
//********************RocketsCollisionFrame.java***************/
import javax.swing.JFrame;
public class RocketsCollisionFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Rockets collision");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RocketsCollisionPanel());
frame.pack();
frame.setVisible(true);
}
}
//*******************RocketsCollisionPanel.java**************/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class RocketsCollisionPanel extends JPanel {
private final int WIDTH = 600, HEIGHT = 600;
private final int DELAY = 20;
private int[] xValues = {15,25,25,5,5};
private int[] yValues = {5,15,55,55,15};
private int[] x2Values = {285, 295, 295, 275, 275};
private int deltaX1, deltaY1, deltaX2, deltaY2;
Polygon rocket1, rocket2;
private Timer timer;
public RocketsCollisionPanel() {
timer = new Timer(DELAY, new CollisionListener());
rocket1 = new Polygon(xValues, yValues, xValues.length);
rocket2 = new Polygon(x2Values, yValues, xValues.length);
deltaX1 = deltaY1 = deltaX2 = deltaY2 = 5;
setBackground(Color.BLACK);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillPolygon(rocket1);
g.setColor(Color.BLUE);
g.fillPolygon(rocket2);
}
private class CollisionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
rocket1.translate(deltaX1, deltaY1);
rocket2.translate(deltaX2, deltaY2);
Rectangle r1 = rocket1.getBounds();
Rectangle r2 = rocket2.getBounds();
if (r1.intersects(r2)) {
deltaX1 *= -1;
deltaX2 *= -1;
deltaY1 *= -1;
deltaY2 *= -1;
}
Point topLeftCornerR1 = r1.getLocation();
Point topLeftCornerR2 = r2.getLocation();
double x1 = topLeftCornerR1.getX();
double y1 = topLeftCornerR1.getY();
double x2 = topLeftCornerR2.getX();
double y2 = topLeftCornerR2.getY();
if(x1 <= 0 || x1 >= WIDTH - 20)
deltaX1 *= -1;
if(y1 <= 0 || y1 >= HEIGHT - 50)
deltaY1 *= -1;
if(x2 <= 0 || x2 >= WIDTH - 20)
deltaX2 *= -1;
if(y2 <= 0 || y2 >= HEIGHT - 50)
deltaY2 *= -1;
repaint();
}
}
}