I have made a program to bounce two balls ,but on running the program it is just showing the two balls and they are not moving , I am not able to understand what is the problem? Is there any problem in start of runnable because when I run only single ball it ran whithout implementing Runnable interface but its not working for two why?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Jpanel extends JPanel implements Runnable{
Thread t1;
Thread t2;
JFrame frame;
Jpanel jp;
int x=0;
int y=0;
Ball ball=new Ball(this);
Ball1 ball1=new Ball1(this);
void move1(){
ball.move();
}
void move2(){
ball1.move();
}
public void paint(Graphics g){
super.paint(g);
setBackground(Color.black);
Graphics2D g2d=(Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g);
ball1.paint(g);
//super.paint(g);//agar yaha to puri screen pehle jaisi saaf ho jaegi
}
public static void main(String args[]) throws InterruptedException{
Jpanel jp=new Jpanel();
JFrame frame =new JFrame("Chota Bheem");
frame.add(jp);
frame.setBackground(Color.BLACK);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
Jpanel t1=new Jpanel();
Jpanel t2=new Jpanel();
t1.start();
t2.start();
}
public void start() {
System.out.println("inside start");
// TODO Auto-generated method stub
if(t1==null){
t1=new Thread(this,"first");
t1.start();
}
if(t2==null){
t2=new Thread(this,"second");
t2.start();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("inside run");
while(true){
jp.move1();
jp.repaint();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
jp.move2();
jp.repaint();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Ball1{
Jpanel jps;
int x=0,y=0,xs=-1,ys=-1;
public Ball1(Jpanel jpanel) {
// TODO Auto-generated constructor stub
this.jps=jpanel;
}
public void move(){
if(x+xs<0){xs=1;}
else if(y+ys<0){y=-1;}
else if(x+xs>jps.getWidth()-30){xs=-1;}
else if(y+ys>jps.getHeight()-30){ys=-1;}
x=x+xs;
y=y+ys;
}
void paint(Graphics g){
g.setColor(Color.darkGray);
g.fillOval(x, y, 60, 60);
}
}
class Ball{
int x=0;
int xs=-1,ys=-1;
int y=0;
JPanel jpn;
Ball(JPanel jpn){
this.jpn=jpn;
}
public void move() {
if(x+xs<0){
xs=1;
}
else if(y+ys<0){
ys=1;
}
else if(x+xs>jpn.getWidth()-30){
xs=-1;
}
else if(y+ys>jpn.getHeight()-30){
ys=-1;
}
x=x+xs;
y=y+ys;
}
public void paint(Graphics g) {
jpn.setBackground(Color.black);
g.setColor(Color.blue);
g.fillOval(x, y, 50, 50);
}
}
}