gpt4 book ai didi

Java 平台游戏不运行最初的几行代码...?

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:03 24 4
gpt4 key购买 nike

我正在为 Java 中的 2d 平台游戏制定基本轮廓...我遇到了一个最近才开始出现的问题!有时,当我运行我的程序时,我的框架出现,一切都设置好了,你可以看到那个家伙,但由于某种原因,地面没有被“添加”(我有一个 addGround() 方法,我在运行的第一个段中调用它)。随着我对游戏的深入,这种情况开始越来越多地发生,直到现在,大多数时候它都会失败并且不会显示/添加地面!但有时,它可以完美地完成任务。

这是它工作时的样子:

大多数时候,当它不起作用时,它看起来就是这样:

所以,这是我的主类代码:(我没有包括所有的进口和东西,只是核心)

    public BusiWorld()
{
this.setFocusable(true);
if(init)
{
ground.addGround(x-300, y+100, 35, 1);
ground.addGround(x-100, y-360, 1, 46);
ground.addGround(x+100, y+90, 1, 1);
ground.addGround(x+400, y+20, 2, 1);
ground.addGround(x+460, y-50, 2, 1);
ground.addGround(x+520, y-120, 2, 1);
ground.addGround(x+460, y-190, 2, 1);
ground.addGround(x+140, y-260, 15, 1);
ground.addGround(x, y-280, 1, 1);
init = false;
}
t = new Timer(16, new ActionListener() {

@Override
public void actionPerformed(ActionEvent ae) {
repaint();
}
});
t.start();
}
public static void main(String[] args)
{
mainFrame.setTitle("Busiworld");
mainFrame.setSize(600,500);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setBackground(Color.WHITE);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
}

这是地面类代码:

public class Ground extends JFrame
{
private Image groundImg = Toolkit.getDefaultToolkit().getImage("ground.png");
private ArrayList<Point> groundLocs = new ArrayList<Point>();
public Ground()
{

}
public void addGround(int xCoord, int yCoord, int howManyWide, int howManyTall)
{
for(int i = 0; i < howManyWide; i++)
{
for(int j = 0; j < howManyTall; j++)
{
groundLocs.add(new Point(xCoord+i*groundImg.getWidth(null), yCoord+j*groundImg.getHeight(null)));
}
}
}
public void drawGround(Graphics g)
{
for(Point p: groundLocs)
{
g.drawImage(groundImg, p.x, p.y, this);
}
}
public int groundArraySize()
{
return groundLocs.size();
}
public Point getGroundArray(int index)
{
return groundLocs.get(index);
}
}

最佳答案

这是 Swing 中的 JFrame?例如,当您调用 repaint() 时,我没有看到 invokeLater()。在 Swing 应用程序中不正确管理线程可能会导致各种各样的问题。鉴于您发布的代码量,我建议您首先处理线程 - 然后如果问题仍然存在,您可以缩小问题范围。

这是一个tutorial on how to manage threads in Swing .

编辑:

基本上,任何修改或导致任何绘制发生的事情都必须在 Swing 组件初始化之前或在事件分派(dispatch)线程上发生。事件监听器中的代码或通过 invokeLater()invokeAndWait() 调用的代码在事件分派(dispatch)线程上运行。 Timer 中的代码不会在事件分派(dispatch)线程上调用,但会与 Swing 组件交互,因此可能会导致各种错误(例如删除一半的绘图)。

关于Java 平台游戏不运行最初的几行代码...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11376807/

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