gpt4 book ai didi

Java重力错误

转载 作者:行者123 更新时间:2023-12-01 09:06:54 25 4
gpt4 key购买 nike

我的重力等级有问题,每当用户跳跃时,它应该改变 y 坐标,直到到达底座,但是当我反复按下跳跃按钮 (W) 时,它会出现错误,并且立方体会继续下降到底座下方。

主类:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

@SuppressWarnings("serial")
public class Frame extends JFrame implements Runnable{ //main class

static Panel panel;
static Frame frame;

//CONSTRUCTOR
Frame(){ //constructor

super("Game Frame");
setLayout(new GridLayout(1,1));

panel = new Panel();

add(panel);

} //constructor

public static void main (String args[]){ //main method

frame = new Frame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(true);
frame.setSize(500,300);
frame.setLocationRelativeTo(null);
Thread T1 = new Thread(frame);
T1.start();

} //main method


public void run(){ //run method

frame.addKeyListener(new KeyListener(){ //key listener method

@Override
public void keyPressed(KeyEvent arg0) { //key pressed

switch(arg0.getKeyChar()){

//A (LEFT)
case 'a':
panel.x -= 10;
panel.repaint();break;

//D (RIGHT)
case 'd':
panel.x += 10;
panel.repaint();break;

//W (UP)
case 'w':
panel.y -= 40;
panel.repaint();
Thread T1 = new Thread(new Gravity());
T1.start();

} //switch

} //key pressed method

@Override
public void keyReleased(KeyEvent arg0) {}

@Override
public void keyTyped(KeyEvent arg0) {}

}); //key listener method
} //run method
} //main class

面板类:

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

@SuppressWarnings("serial")
public class Panel extends JPanel{ //class

static BufferedImage bg;
static int x = 20;
static int y = 195;


//PAINT METHOD
public void paint(Graphics g){ //method

super.paint(g);
g.setColor(Color.ORANGE);
this.setBackground(Color.BLACK);

//IMPORTING IMAGES
try {
bg = ImageIO.read(getClass().getResourceAsStream("Background.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//DRAWING GAME
g.drawImage(bg, 0, 0,500,275,null);
g.fillRect(x, y, 50, 50);

} //method




} //class

重力等级:

public class Gravity implements Runnable{ //class

@Override
public void run() { //run method

while(Frame.panel.y != 195){ //while loop

try {
Thread.sleep(100);
} catch (InterruptedException e) { //catch exception
// TODO Auto-generated catch block
e.printStackTrace();
} //catch exception

Frame.panel.y += 5;
Frame.panel.repaint();

} //while loop

} //run method

} //class

最佳答案

我建议您不要创建多个线程,而应重用一个线程。可能发生的情况是两个线程修改了 Frame.panel.y。第一个将其移动到 195,而第二个正在 sleep ,然后第二个将其移动到 200 并且满足您的 !=195 条件。稍后在框架之外绘画会发生崩溃。一个简单的解决方法是将“while(Frame.panel.y != 195)”替换为“while(Frame.panel.y < 195)”

关于Java重力错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41198043/

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