我制作了一个弹跳两个球的程序,但是在运行程序时它只是显示两个球并且它们没有移动,我无法理解这是什么问题? 在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);
}
}
}
答案 0 :(得分:1)
Jpanel
类Runnable
并不是正确的方法。您想要做的是让Ball
类可以运行,并且以与屏幕上的绘图内容完全分离的方式更新其位置。混合渲染和移动并不是一个很好的关注点分离。只是让你的球担心它在哪里以及它在哪里移动,让UI担心绘制它的位置。Thread
课程中声明的Jpanel
个实例甚至无法使用。Thread.sleep(1)
毫无意义。如果你在屏幕上画球并且你只是在球运动之间等待大约1毫秒,为什么要睡觉呢?如果你没有使用多个线程,你可以睡一段合理的时间(比如大约1/60秒),或者你可以一直全速运行。