I am trying to create a java program, using Netbeans, with two balls (one position at the top and the other bottom) and when executed they move in the opposite direction and go offscreen.
The original code was given to us using one ball and we were asked to add a second panel hence the confusion within the code.
My problem is when I execute the code using BoxLayout.Y_AXIS
the balls meet in center and disappear due to the panel arrangement. I want the balls to cross the center into the other panels.
I have tried using border layout
, but i loose one ball.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RandomBall {
JFrame frame;
public int x = 0;
public int y = 0;
public int z = 300;
public int deltaX;
public int deltaY;
public int deltaZ;
public int posNeg;
public int diameter = 50;
final static public int MULT = 5;
Ball1DrawPanel drawPanel1;
Ball2DrawPanel drawPanel2;
JPanel pan;
public static void main(String[] args) {
RandomBall gui = new RandomBall();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel1 = new Ball1DrawPanel();
drawPanel2 = new Ball2DrawPanel();
pan = new JPanel();
pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS));
pan.add(BorderLayout.NORTH, drawPanel1);
pan.add(BorderLayout.SOUTH, drawPanel2);
frame.getContentPane().add(BorderLayout.CENTER, pan);
frame.setSize(500, 500);
frame.setVisible(true);
deltaX = (int) (Math.random() * MULT); //randomly set the displacement in the x direction (across)
deltaY = (int) (Math.random() * MULT); //randomly set the displacement in the y direction (down)
deltaZ = (int) (Math.random() * MULT); //randomly set the displacement in the y direction (down)
while ((deltaX == 0) && (deltaY == 0)) {
deltaX = (int) (Math.random() * MULT); //to prevent both values being zero - ball will not move
deltaY = (int) (Math.random() * MULT);
deltaZ = (int) (Math.random() * MULT);
}
posNeg = (int) (Math.random() * 2);
if (posNeg == 0) {
deltaX = deltaX * -1; //randomly set the direction to left or right
}
}
public RandomBall() {
go();
}
class Ball1DrawPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
g.setColor(Color.red);
g.fillOval((this.getWidth() + (x) - diameter) / 2, (0 + (y)) / 2, diameter, diameter);
frame.repaint();
x = x + deltaX;
y = y + deltaY;
}
}
class Ball2DrawPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
g.setColor(Color.BLUE);
g.fillOval((this.getWidth() + (x) - diameter) / 2, (0 + (z)) / 2, diameter, diameter);
frame.repaint();
x = x + deltaX;
z = z - deltaZ;
}
}
}
Is there any layout
, or any implementation, I can use that will allow the balls to cross into the opposite applet rather than breaking at the center when the collide with the other?