Java Circle to Circle collision detection - java

I am making a circle to circle collision detection program. I can get the balls to move around but when the collision is detected, the balls are quite far overlapped. Any suggestions? Thanks in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.lang.Math;
public class ShapePanel extends JPanel{
private JButton button, startButton, stopButton;
private JTextField textField;
private JLabel label;
private Timer timer;
private final int DELAY = 10;
ArrayList<Shape> obj = new ArrayList<Shape>();
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ShapePanel());
frame.pack();
frame.setVisible(true);
}
public ShapePanel(){
JPanel controlPanel = new JPanel();
DrawingPanel dpanel = new DrawingPanel();
controlPanel.setPreferredSize(new Dimension(100,400));
button = new JButton("Add Shape");
startButton = new JButton("Start");
stopButton = new JButton("Stop");
textField = new JTextField(2);
label = new JLabel("Count:");
controlPanel.add(button);
controlPanel.add(label);
controlPanel.add(textField);
controlPanel.add(startButton);
controlPanel.add(stopButton);
add(controlPanel);
add(dpanel);
ButtonListener bListen = new ButtonListener();
button.addActionListener(bListen);
startButton.addActionListener(bListen);
stopButton.addActionListener(bListen);
timer = new Timer(DELAY, bListen);
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button){
obj.add(new Shape());
if (obj.get(obj.size()-1).y > 200){
obj.get(obj.size()-1).moveY = -obj.get(obj.size()-1).moveY;
}
}else if (e.getSource() == timer){
for (int i = 0; i < obj.size(); i++){
obj.get(i).move();
}
for (int i = 0; i < obj.size(); i++){
for (int j = i + 1; j < obj.size(); j++){
if (Math.sqrt(Math.pow((double)obj.get(i).centerCoordX - (double)obj.get(j).centerCoordX,2)) +
Math.pow((double)obj.get(i).centerCoordY - (double)obj.get(j).centerCoordY,2) <= obj.get(i).radius + obj.get(j).radius){
timer.stop();
}
}
}
}else if (e.getSource() == startButton){
timer.start();
}else if (e.getSource() == stopButton){
timer.stop();
}
repaint();
}
}
private class DrawingPanel extends JPanel{
DrawingPanel(){
setPreferredSize(new Dimension(400,400));
setBackground(Color.pink);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int i = 0; i < obj.size(); i++){
obj.get(i).display(g);
}
}
}
}
import java.awt.*;
import java.util.*;
public class Shape{
public int x, y, width, height, moveX = 1, moveY = 1, centerCoordX, centerCoordY, radius;
private Color colour;
public boolean reverse = false, sameDirection = true;
Random generator = new Random();
public int randomRange(int lo, int hi){
return generator.nextInt(hi-lo)+lo;
}
Shape(){
width = randomRange(30, 50);
if (width % 2 != 0){
width = randomRange(30, 50);
}
height = width;
radius = width/2;
x = randomRange(0, 400-width);
y = randomRange(0, 400-height);
colour = new Color(generator.nextInt(256),generator.nextInt(256),generator.nextInt(256));
}
public void display(Graphics g){
g.setColor(colour);
g.fillOval(x, y, width, height);
}
void move(){
x += moveX;
y += moveY;
centerCoordX = x + width/2;
centerCoordY = y + height/2;
if(x >= 400-width){
moveX = -moveX;
}if(x <= 0){
moveX = -moveX;
}if(y >= 400-height){
moveY = -moveY;
}if (y <= 0){
moveY = -moveY;
}
}
}

So much uncommented code!
The balls are just colliding if their centres are within the sum of the radii. Let r1 and r2 be the ball radii, and x1, y1 the position of the centre of ball1; similarly x2, y2 for ball2.
Measure the square of the distance between the centres as (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1). (Pythagoras).
They have collided if this is less than or equal to (r1 + r2) * (r1 + r2).
The key thing here is that there is no need to compute the square roots which is an expensive computational task.

I'd say it probably due to your circles moving too fast or your time step is too high. Reduce your time step. A better approach is use a physics library like Box2D. Have a look at libgdx, that a java library that has it included.
its discussed a bit in this link

You should check the colision after each move.
for (int i = 0; i < obj.size(); i++)
{
obj.get(i).move();
for (int j = 0; j < obj.size(); j++)
{
if (Math.sqrt(Math.pow((double)obj.get(i).centerCoordX - (double)obj.get(j).centerCoordX,2)) +
Math.pow((double)obj.get(i).centerCoordY - (double)obj.get(j).centerCoordY,2) <= obj.get(i).radius + obj.get(j).radius && i!=j)
{
timer.stop();
}
}
}

You need something like this.
public boolean overlaps (Circle c1, Circle c2) {
float dx = c1.x - c2.x;
float dy = c1.y - c2.y;
float distance = dx * dx + dy * dy;
float radiusSum = c1.radius + c2.radius;
return distance < radiusSum * radiusSum;
}

Related

Coloring a Triangle with 3 colors

Please help me how to color the triangle with the three colors. I have it as a problem for school,
Use Java programming language
Hello this is the code:
I am trying to fill the triangle with the three colors, but is hard to mix colors to get it. Please if you are to solve it(approximate it) as much as you can send it to me, i have it as a homework and 5-6 days deadline
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.geom.*;
public class NotFullVersion2 extends JApplet {
public static void main(String s[]) {
JFrame frame = new JFrame();
frame.setTitle("Colors");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet applet = new NotFullVersion2();
applet.init();
applet.addMouseListener(
new MouseAdapter(){
public void mousePressed(MouseEvent e) {
System.out.println(e.getX() + " " + e.getY());
}});
frame.getContentPane().add(applet);
frame.pack();
frame.setVisible(true);
}
ColorPanel panel;
public void init() {
panel = new ColorPanel();
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(panel, BorderLayout.CENTER);
JPanel p = new JPanel();
cp.add(p,BorderLayout.EAST);
}
}
class ColorPanel extends JPanel {
//int red = 100,green = 100, blue = 100;
public ColorPanel() {
setPreferredSize(new Dimension(500, 500));
setBackground(Color.black);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for(int i = 0; i < 256; i++) {
int start = 399;
g2.setColor(new Color(0,i,255-i));
for(int j = 0; j < 200; j ++) {
Rectangle rec = new Rectangle(150+j,start - i,1,1);
g2.fill(rec);
}
}
for(int j = 0; j < 100; j++) {
int start = 100;
for(int i = 0; i < 300; i++) {
if(i < 22) {
g2.setColor(new Color(255,0,0));
Rectangle rec = new Rectangle(100 + i,start + j,1,1);
g2.fill(rec);
} else if(i > 21 && i < 278) {
g2.setColor(new Color(255-(i-22),(i-22),0));
Rectangle rec = new Rectangle(100 + i,start + j,1,1);
g2.fill(rec);
} else if(i < 300) {
g2.setColor(new Color(0,255,0));
Rectangle rec = new Rectangle(100 + i,start + j,1,1);
g2.fill(rec);
}
}
}
GeneralPath closePath1a = new GeneralPath();
g2.setColor(new Color(0,0,0));
closePath1a.moveTo(100,100);
closePath1a.lineTo(100,400);
closePath1a.lineTo(250,400);
closePath1a.closePath();
g2.fill(closePath1a);
GeneralPath closePath2a = new GeneralPath();
g2.setColor(new Color(0,0,0));
closePath2a.moveTo(400,100);
closePath2a.lineTo(400,400);
closePath2a.lineTo(250,400);
closePath2a.closePath();
g2.fill(closePath2a);
GeneralPath closePath3a = new GeneralPath();
g2.setColor(new Color(0,0,0));
closePath3a.moveTo(100,100);
closePath3a.lineTo(100,50);
closePath3a.lineTo(400,50);
closePath3a.lineTo(400,100);
closePath3a.closePath();
g2.fill(closePath3a);
}
}
Coloring a triangle like this is equivalent to calculating the barycentric coordinates of each pixel within the triangle. The following untested code calculates the barycentric coordinates for each pixel within the triangle ABC, and then uses it to color that pixel:
private float area(float Ax, float Ay, float Bx, float By, float Cx, float Cy) {
return 0.5*((Ax - Cx)*(By - Ay) - (Ax - Bx)*(Cy - Ay));
}
private void paintTriangle(Graphics g, float Ax, float Ay, float Bx, float By, float Cx, float Cy) {
// calculate the bounding box of the triangle:
int minX = Math.round(Math.min(Ax, Math.min(Bx, Cx)));
int minY = Math.round(Math.min(Ay, Math.min(By, Cy)));
int maxX = Math.round(Math.max(Ax, Math.max(Bx, Cx)));
int maxY = Math.round(Math.max(Ay, Math.max(By, Cy)));
// loop for each pixel in the bounding box of the triangle
for(int y = minY; y < maxY; ++y) {
for(int x = minX; x < maxX; ++x) {
// center of the pixel (x,y)
float Px = x + 0.5, Py = y + 0.5;
// barycentric coordinates of P
float denom = area(Ax, Ay, Bx, By, Cx, Cy);
float b0 = area(Px, Py, Bx, By, Cx, Cy)/denom;
float b1 = area(Ax, Ay, Px, Py, Cx, Cy)/denom;
float b2 = area(Ax, Ay, Bx, By, Px, Py)/denom;
// discard pixels outside the triangle
if(b0 < 0 || b1 < 0 || b2 < 0)
continue;
// paint a pixel of color (b0,b1,b2) at (x,y)
g.setColor(new Color(b0,b1,b2));
g.fillRect(x,y,1,1));
}
}
}
I'll leave it to you to test and integrate this code.
You can read more about barycentric coordinates on wikipedia;

KeyListener doesn't respond

I have written some code that makes labyrinth and fills the JPanel with my figures Wall, Player, Road and Gate. I want to move the player by pressing the keys W,A,S,D.
The frame gets drawn but the player is not moving:
Sprite[][] spr = fr.read();
int x1 = fr.row;
int y1 = fr.col;
fr.close();
GameFrame gf = new GameFrame(spr, x1, y1);
x1 = (x1 * 20) + 30;
y1 = (y1 * 20);
JFrame frame = new JFrame();
frame.setTitle("Lab");
frame.setSize(new Dimension(y1, x1));
frame.setPreferredSize(new Dimension(y1, x1));
frame.addKeyListener(gf);
frame.setFocusable(true);
frame.add(gf);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
public void paint(Graphics g) {
int a13 = 5;
int a14 = 5;
Player pl = new Player();
super.paintComponent(g);
for (int i = 0; i < i1; i++) {
for (int i0 = 0; i0 < i2; i0++) {
Sprite currentSpr1 = sprites[i][i0];
X = currentSpr1.setXCoord(i);
Y = currentSpr1.setYCoord(i0);
H = currentSpr1.setHeight();
W = currentSpr1.setWidth();
if (currentSpr1 == pl) {
addKeyListener(this);
}
currentSpr1.YourPaint(g, X, Y, H, W);
}
}
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
if (c == KeyEvent.VK_W) {
Y = Y - 20;
System.out.print("lol");
repaint();
}
if (c == KeyEvent.VK_S) {
Y = Y + 20;
//repaint();
}
if (c == KeyEvent.VK_D) {
X = X + 20;
//repaint();
}
if (c == KeyEvent.VK_A) {
X = X - 20;
//repaint();
}
//if (sprite instanceof Wall){
//}*/
}
Well, it's a bit hard to understand your code, but firstly:
In your keyPressed method you're incrementing X or Y, but in your update method you're resetting X and Y, so this will have no effect.
And what's gf? Is it the class above. You should add "this" as a keylistener.

Button To Reset The View Of JFrame

I have to write a program that will generate 20 random circles with random radius lengths. If any of these circles intersect with another, the circle must be blue, and if it does not intersect, the color is red. I must also place a button on the JFrame. If this button is pressed, it needs to clear out the JFrame, and generate a new set of 20 circles following the same color rules. I am extremely new to Java Swing and am really stuck. I have everything working except the button. I cannot get a new set of circles to generate. Any help would be greatly appreciated. Thank You.
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class IntersectingCircles extends JPanel
{
private int[] xAxis = new int [20]; // array to hold x axis points
private int[] yAxis = new int [20]; // array to hold y axis points
private int[] radius = new int [20]; // array to hold radius length
public static void main (String[] args)
{
JFrame frame = new JFrame("Random Circles");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new IntersectingCircles());
frame.pack();
frame.setVisible(true);
}
public IntersectingCircles()
{
setPreferredSize(new Dimension(1000, 800)); // set window size
Random random = new Random();
// Create coordinates for circles
for (int i = 0; i < 20; i++)
{
xAxis[i] = random.nextInt(700) + 100;
yAxis[i] = random.nextInt(500) + 100;
radius[i] = random.nextInt(75) + 10;
}
}
public void paintComponent(Graphics g)
{
// Add button to run again
JButton btnAgain = new JButton("Run Again");
btnAgain.setBounds(850, 10, 100, 30);
add(btnAgain);
btnAgain.addActionListener(new ButtonClickListener());
// Determine if circles intersect, create circles, color circles
for (int i = 0; i < 20; i++)
{
int color = 0;
for (int h = 0; h < 20; h++)
{
if(i != h)
{
double x1 = 0, x2 = 0, y1 = 0, y2 = 0, d = 0;
x1 = (xAxis[i] + radius[i]);
y1 = (yAxis[i] + radius[i]);
x2 = (xAxis[h] + radius[h]);
y2 = (yAxis[h] + radius[h]);
d = (Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1)*(y2 - y1))));
if (d > radius[i] + radius[h] || d < (Math.abs(radius[i] - radius[h])))
{
color = 0;
}
else
{
color = 1;
break;
}
}
}
if (color == 0)
{
g.setColor(Color.RED);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
else
{
g.setColor(Color.BLUE);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
}
}
private class ButtonClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if(action.equals("Run Again"))
{
new IntersectingCircles();
}
}
}
}
Suggestions:
Give your class a method that creates the random circles and calls repaint()
This method should create the circles and add them into an ArrayList.
Consider using Ellipse2D to represent your circles, and so you'd have an ArrayList<Ellipse2D>.
Call this method in your class constructor.
Call it again in the button's ActionListener.
Never add button's or change the state of your class from within your paintComponent method. This method is for drawing the circles and drawing them only and nothing more. Your way you will be creating the button each time the paintComponent method is called, so you could be potentially needlessly creating many JButtons
and needlessly slowing down your time-critical painting method.
Instead add the button in the constructor.
Be sure to call super.paintComponent(g) in your paintComponent method as its first call. This will clear the old circles when need be.
Also in paintComponent, iterate through the ArrayList of circles, drawing each one.
After some searching on this website, i found what i needed. Everything seems to work now. Thanks.
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class IntersectingCircles extends JPanel
{
private int[] xAxis = new int [20]; // array to hold x axis points
private int[] yAxis = new int [20]; // array to hold y axis points
private int[] radius = new int [20]; // array to hold radius length
public static void main (String[] args)
{
JFrame frame = new JFrame("Random Circles");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 800));
ActionListener runAgain = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent c)
{
frame.getContentPane().add(new IntersectingCircles());
frame.pack();
}
};
JButton btnAgain = new JButton("Run Again");
btnAgain.setBounds(850, 10, 100, 30);
btnAgain.addActionListener(runAgain);
frame.add(btnAgain);
frame.getContentPane().add (new IntersectingCircles());
frame.pack();
frame.setVisible(true);
}
public IntersectingCircles()
{
Random random = new Random();
// Create coordinates for circles
for (int i = 0; i < 20; i++)
{
xAxis[i] = random.nextInt(700) + 100;
yAxis[i] = random.nextInt(500) + 100;
radius[i] = random.nextInt(75) + 10;
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Determine if circles intersect, create circles, color circles
for (int i = 0; i < 20; i++)
{
int color = 0;
for (int h = 0; h < 20; h++)
{
if(i != h)
{
double x1 = 0, x2 = 0, y1 = 0, y2 = 0, d = 0;
x1 = (xAxis[i] + radius[i]);
y1 = (yAxis[i] + radius[i]);
x2 = (xAxis[h] + radius[h]);
y2 = (yAxis[h] + radius[h]);
d = (Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1)*(y2 - y1))));
if (d > radius[i] + radius[h] || d < (Math.abs(radius[i] - radius[h])))
{
color = 0;
}
else
{
color = 1;
break;
}
}
}
if (color == 0)
{
g.setColor(Color.RED);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
else
{
g.setColor(Color.BLUE);
g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2);
}
}
}
}
private class ButtonClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
Maybe you can have a try...

Closest pair of points using mouse clicks

The assignment is to to a closest pair of points using brute force.
I seem to have most everything I need - the frame appears, circles appear where I click, and the closest pairs seem to highlight properly, I say "seems" because this is where my question lies. I need only two circles highlighted at any given time (the closest pair), but previous closest pairs do not de-select/unhighlight.
I hope this is something simple I have overlooked. I have been at this for a while, so it's very possible my mind and eyes are just too tired to pick this problem up. Hopefully, a fresh set of eyes will do me some good.
Any help is greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class AssignmentFour extends JFrame {
private final PointPanel canvas = new PointPanel();
public AssignmentFour() {
JPanel panel = new JPanel();
this.add(canvas, BorderLayout.CENTER);
this.add(panel, BorderLayout.SOUTH);
add(new JLabel("<html> Click anywhere within the panel."
+ "<BR> The two closest points will be highlighted.<BR>"
+ "Click the 'x' to exit program. </html>"), BorderLayout.SOUTH);
}//AssignmentFour method
public static void main(String[] args) {
AssignmentFour frame = new AssignmentFour();
frame.setTitle("Closest points");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setVisible(true);
}//main
class PointPanel extends JPanel {
private int xCoordinate = 200;
private int yCoordinate = 200;
private int radius = 5;
private Graphics g;
double minDist = 999999999;
ArrayList<Point> points = new ArrayList<>();
Point ClosestPoint1, ClosestPoint2;
public final double distBetweenPoints(int x, int y, int a, int b) {
double theDist = 0.0;
theDist = Math.sqrt(Math.pow(a - x, 2) + Math.pow(y - b, 2));
return theDist;
}//distBetweenPoints method
public PointPanel() {
addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
xCoordinate = e.getX();
yCoordinate = e.getY();
Point newCoord = e.getPoint();
points.add(newCoord);
g = getGraphics();
g.setColor(Color.RED);
g.drawOval(xCoordinate, yCoordinate, radius, radius);
//g.dispose();
if (points.size() >= 2) {
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
Point p = points.get(i);
Point q = points.get(j);
int x1 = p.x;
int y1 = p.y;
int a1 = q.x;
int b1 = q.y;
if (distBetweenPoints(x1, y1, a1, b1) < minDist) {
minDist = distBetweenPoints(x1, y1, a1, b1);
ClosestPoint1 = p;
ClosestPoint2 = q;
}//inner if
else {
}//else
}//for 'j'
}// for 'i'
int x2 = ClosestPoint1.x;
int y2 = ClosestPoint1.y;
int a2 = ClosestPoint2.x;
int b2 = ClosestPoint2.y;
g.fillOval(x2, y2, radius, radius);
g.fillOval(a2, b2, radius, radius);
}//if
}//mouseReleased
}//MouseListener
);
}//pointPanel
}//point panel extend
}//assignmentfour class
Don't use getGraphics to perform
Custom painting, this is not how painting in Swing is done
Instead, override the JPanels paintComponent method and put your custom painting within it
Take a look at Performing Custom Painting for more details

Implementation of Galton board in java

I am writing the implementation of Galton Board in Java by using Java awt, Swing and thread. My Program has three text field to choose number of slots, number of balls, and number of ball drops at the same time, two buttons one for display and one for start the program. I try to make it work like I can choose the amount of balls and click start and the balls auto falling down the chimney. Currently, My program be able to drop one ball and running fine, but I don't know how to implement that be able drop more than one ball. Any suggestions or help are appreciated, Thank you. This is Main.Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;
public class Main extends JFrame {
private String num_slots;
private String num_balls;
private String ball_free;
private JButton Display;
private JButton Start;
private JPanel textpanel;
private JPanel mainpanel;
private JPanel graphpanel;
public Main() {
textpanel = new JPanel();
textpanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
textpanel.add(new JLabel("Number of Slots"));
final JTextField text1 = new JTextField(10);
textpanel.add(text1);
textpanel.add(new JLabel("Number of Balls"));
final JTextField text2 = new JTextField(10);
textpanel.add(text2);
textpanel.add(new JLabel("How many balls can be freed"));
final JTextField text3 = new JTextField(10);
textpanel.add(text3);
Display = new JButton("Display");
textpanel.add(Display);
Start = new JButton("Start");
textpanel.add(Start);
// Create panel p2 to hold a text field and p1
mainpanel = new JPanel(new BorderLayout());
mainpanel.add(textpanel, BorderLayout.NORTH);
/*
* graphpanel = new JPanel(); graphpanel.setLayout(new
* BoxLayout(graphpanel, BoxLayout.Y_AXIS));
*/
add(mainpanel, BorderLayout.CENTER);
Display.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Display) {
num_slots = text1.getText();
int slots = Integer.parseInt(num_slots);
num_balls = text2.getText();
int balls = Integer.parseInt(num_balls);
MainPanel pa = new MainPanel(slots, balls);
mainpanel.add(pa);
mainpanel.revalidate();
}
}
});
Start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Start) {
num_slots = text1.getText();
int slots = Integer.parseInt(num_slots);
num_balls = text2.getText();
int balls = Integer.parseInt(num_balls);
MainPanel pa = new MainPanel(slots, balls);
mainpanel.add(pa, BorderLayout.CENTER);
pa.start();
mainpanel.revalidate();
mainpanel.repaint();
}
}
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Main frame = new Main();
frame.setTitle("The Galton board");
frame.setSize(1000, 800);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setAutoRequestFocus(true);
}
}
main panel class contains the chimneys and balls
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;
class MainPanel extends JPanel implements Runnable {
private int num;
private int number_ball;
public static int start_y = 100;
private float ball_x = 385;
private float ball_y = 50;
private float radius = 15;
private static int panel_x = 300;
private static int panel_y = 100;
private int diameter = 20;
private int last_x = 0;
private final static Random generator = new Random();
ArrayList<Balls> list_ball = new ArrayList<Balls>();
private int m_interval = 100;
private Timer m_timer;
public MainPanel() {
}
public MainPanel(int number) {
num = number;
}
public MainPanel(int number, int ball) {
num = number;
number_ball = ball;
for (int i = 1; i <= number_ball; i++)
{
list_ball.add(new Balls());
}
m_timer = new Timer(m_interval, new TimerAction());
}
public int getPanel_y() {
return panel_y;
}
public void start()
{
m_timer.setInitialDelay(250);
m_timer.start();
}
#Override
protected void paintComponent(Graphics g) {
int start_y = 100;
panel_x = 300;
panel_y = 100;
diameter = 20;
last_x = 0;
super.paintComponent(g);
if (num % 2 == 0) {
for (int i = 1; i <= num; i++) {
if ((i % 2) != 0) {
for (int k = 1; k <= num; k++) {
g.setColor(Color.BLUE);
g.fillOval(panel_x, panel_y, diameter, diameter);
panel_x = panel_x + 40;
}
} else if ((i % 2) == 0) {
for (int k = 1; k <= num + 1; k++) {
g.setColor(Color.BLUE);
g.fillOval(panel_x - 20, panel_y, diameter, diameter);
panel_x = panel_x + 40;
}
}
panel_y = panel_y + 40;
panel_x = 300;
}
} else if (num % 2 != 0) {
for (int i = 1; i <= num; i++) {
if ((i % 2) != 0) {
for (int k = 1; k <= num; k++) {
g.setColor(Color.BLUE);
g.fillOval(panel_x, panel_y, diameter, diameter);
panel_x = panel_x + 40;
}
} else if ((i % 2) == 0) {
for (int k = 1; k <= num + 1; k++) {
g.setColor(Color.BLUE);
g.fillOval(panel_x - 20, panel_y, diameter, diameter);
panel_x = panel_x + 40;
}
}
panel_y = panel_y + 40;
panel_x = 300;
}
}
for (int n = 40; n < panel_y - 40; n = n + 40) {
if (num % 2 == 0) {
g.drawLine(panel_x - 50 + n, panel_y - 10, panel_x - 50 + n,
panel_y + 80);
g.drawLine(panel_x, panel_y + 80, panel_x - 50 + n, panel_y + 80);
last_x = panel_x - 50 + n;
} else if (num % 2 != 0) {
g.drawLine(panel_x - 30 + n, panel_y - 10, panel_x - 30 + n,
panel_y + 80);
g.drawLine(panel_x, panel_y + 80, panel_x - 30 + n, panel_y + 80);
last_x = panel_x - 30 + n;
}
}
for (int i = 0; i< list_ball.size(); i++)
{
list_ball.get(i).draw(g);
}
}
class TimerAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i< list_ball.size(); i++)
{
list_ball.get(i).move();
//return;
//m_timer.stop();
repaint();
}
}
Balls Class
import java.awt.geom.Ellipse2D;
import java.util.Random;
import java.awt.*;
public class Balls {
private Ellipse2D.Double thisBall;
private int Ball_x;
private int Ball_y;
public int radius;
public int start_y;
private final static Random generator = new Random();
Mainpanel pa = new Mainpanel();
public Balls()
{
start_y = 100;
Ball_x = 385;
Ball_y = 50;
radius = 15;
}
public void draw(Graphics g)
{
g.setColor(Color.RED);
g.fillOval(Ball_x, Ball_y, radius, radius);
}
public void move()
{
if (Ball_y < pa.getPanel_y() + 65)
{
int direction = generator.nextInt(2);
Ball_y = Ball_y + 5;
if (Ball_y == start_y - 10 && start_y < pa.getPanel_y())
{
if (direction == 0)
{
Ball_x = Ball_x - 20;
}
else Ball_x = Ball_x + 20;
start_y = start_y + 40;
}
System.out.println(Ball_y);
System.out.println(pa.getPanel_y());
}
// Ball_x = Ball_x + 5;
}
}
Create a new logical class, not a GUI class, for your Ball, one that does not extend a JPanel or any Swing component, but rather one that has the logic behind the Ball as well as perhaps a rendering method that accepts a Graphics or Graphics2D object. Then give your drawing JPanel class an ArrayList of these Ball objects, move them in your game loop -- note that I would prefer using a Swing Timer and not a background thread, and then in your JPanel's paintComponent method iterate through the ArrayList of Balls, drawing each Ball by calling its rendering method.
As an aside: all your class names should begin with an upper case letter, and all identifiers other than constants should use camel case, so your mainpanel class should be named MainPanel. I've edited your code prettify the code formatting and have made this change for you.
Aside number 2: your current code has code logic inside of paintComponent. Don't do that as that will mess you up. You don't have full control over when or even if paintComponent will be called.

Categories

Resources