gpt4 book ai didi

java - 需要减慢矩形移动

转载 作者:行者123 更新时间:2023-11-29 05:32:37 27 4
gpt4 key购买 nike

我遇到线程问题。我正在尝试重新创建乒乓球,其中有 2 个玩家的 2 个 Action 监听器。 2 个桨以我希望它们移动的速度移动。但是,“球”(上面涂有椭圆形的矩形对象)移动得太快了。我已经尝试使用 Ball 类中的第二个线程来减慢它的速度,但这似乎不起作用。任何帮助,将不胜感激。这是我的代码:

public class BattleBallz extends JFrame implements Runnable {
AL keyListen1 = new AL();
AL2 keyListen2 = new AL2();
Image dbi;
Graphics dbg;

int x1,x2;
int ballX, ballY, direction;
Ball b1;

public BattleBallz(){
setTitle("Battle Ballz");
setSize(350, 400);
setResizable(false);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addKeyListener(keyListen1);
addKeyListener(keyListen2);
x1 = 150;
x2 = 150;
int direction = 0 + (int)(Math.random() * ((2 - 0) + 1));
b1 = new Ball(direction);
Thread b = new Thread(b1);
b.start();
}

public void paint(Graphics g){
dbi = createImage(getWidth(), getHeight());
dbg = dbi.getGraphics();
paintComponent(dbg);
g.drawImage(dbi, 0, 0, this);
}

public void paintComponent(Graphics g){
Rectangle p1 = new Rectangle(x1,375,60,10);
g.setColor(Color.blue);
g.fillRect(x1, 375, 60, 10);
Rectangle p2 = new Rectangle(x2,45,60,10);
g.setColor(Color.red);
g.fillRect(x2,45,60,10);

b1.paintComponent(g, p1, p2);

repaint();
}


@Override
public void run() {
try {
while(true){
move();
Thread.sleep(5);
}
} catch (Exception e) {
// TODO: handle exception
}

}

public void move(){
x1 += keyListen1.getXdirection();
x2 += keyListen2.getXdirection();

if (x1<=0){
x1 =0;
}
if (x1>=305){
x1 = 305;
}
if (x2<=0){
x2=0;
}
if (x2>=305){
x2=305;
}
}
}

public class Ball extends JPanel implements Runnable {

boolean up,down,right,left;
int x = 150, y = 150 ;

public Ball(int direction){
if(direction ==1){
down = true;
}
if (direction ==0){
up = true;
}
}

public void paintComponent(Graphics g, Rectangle p1, Rectangle p2){
super.paintComponents(g);
if(down){
y++;
Rectangle ball = new Rectangle(x,y,49,49);
g.fillOval(x, y, 50, 50);
if (y>=385 || ball.intersects(p1)){
down = false;
up = true;
}
}
if (up){
y--;
Rectangle ball = new Rectangle(x,y,49,49);
g.fillOval(x, y, 50, 50);
if (y<=10 || ball.intersects(p2)){
up = false;
down = true;
}
}
}

@Override
public void run() {
// TODO Auto-generated method stub
try {
while (true){
Thread.sleep(30);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}

最佳答案

  1. 使用 Swing Timer而不是普通的 Thread,您遇到了 Concurency in Swing 的问题,代码发布到阻塞Event Dispatch Thread,被Thread.sleep锁定,无限阻塞

  2. 使用 paintComponent 但放在那里 JPanel,第一。里面的代码行应该是super.paintComponent,否则paint会累积,覆盖JPanel

  3. getPreferredSize
  4. 使用 KeyBindings而不是 KeyListener

关于java - 需要减慢矩形移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20599972/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com