我已經制作了一個彈跳兩個球的程序,但是在運行程序時它只是顯示兩個球而他們沒有移動,我無法理解這是什麼問題? 在runnable開始時是否有任何問題,因爲當我只運行單個球時,它運行沒有實現Runnable接口,但它不適用於兩個爲什麼?球不動爲什麼?
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);
}
}
}
由於一個線程,單球不能運行。我不明白你爲什麼創造Ball1。此外,線程的標題令人難以置信的誤導:) –
爲什麼你有三個Jpanel和四個線程? –
更好地分離JPanel和Runnables,讓程序的每個部分對所有其他部分的暴露程度最低,否則很快就無法看到自己的代碼。只需將Balls/JPanel作爲Runnables的參數即可。 – Trilarion