gpt4 book ai didi

java - 使对象在单击时出现

转载 作者:行者123 更新时间:2023-12-01 13:50:32 25 4
gpt4 key购买 nike

我对 Java 编程非常陌生。我目前正在尝试制作一个游戏,其中白球不断出现在屏幕上,用户必须单击球并将其拖到 Canvas 的右侧以使其消失。我还没有写完代码,但我编写的代码不断使我的 Java 程序崩溃。谁能告诉我我的代码有什么问题以及为什么我的程序不断崩溃?谢谢!

public class BubbleGame extends GraphicsProgram
{

//~ Instance/static variables


private GRect field;
private GRect goal;
private GObject gobj; /* The object being dragged */
private GPoint last; /* The last mouse position */

private RandomGenerator rgen = new RandomGenerator();

//~ Constructor ...........................................................

// ----------------------------------------------------------
/**
* Creates a new BubbleGame object.
*/
public void init()
{
//call method to create regions
CreateRegions();

//add mouse listeners
addMouseListeners();

//loop to add bubbles
while (true)
{
//create a filled bubble
GOval oval = new GOval (100, 100, 50, 50);
oval.setFilled(true);
oval.setColor(Color.WHITE);
add(oval);

//randomly generate coordinates within the field


//add the bubble and pause



}
}


//~ Methods ...............................................................
public void CreateRegions(){

//create and add the field with the size and color of your choice
field = new GRect(0, 0, getWidth() * .75, getHeight());
field.setFilled(true);
field.setColor(Color.GREEN);
add(field);

//create and add the adjacent goal with the size and color of your choice
goal = new GRect(493, 0, getWidth() * .25, getHeight());
goal.setFilled(true);
goal.setColor(Color.BLACK);
add(goal);
}



/* Called on mouse press to record the coordinates of the click */
public void mousePressed(MouseEvent e) {
last = new GPoint(e.getPoint());
gobj = getElementAt(last);
//later add check that not dragging field or goal

}

/* Called on mouse drag to reposition the object */
public void mouseDragged(MouseEvent e) {
if (gobj != null) {
gobj.move(e.getX() - last.getX(), e.getY() - last.getY());
last = new GPoint(e.getPoint());
}

}

/* Called on mouse drag to reposition the object */
public void mouseReleased(MouseEvent e) {
//if gobj has a value and its coordinates are contained by goal, make it invisible




}


}

最佳答案

您的 while 循环可能是其崩溃的原因。你可以考虑在这里设置一个 sleep ,这样你的应用程序就不会不断地使用CPU:

    while (true)
{
//create a filled bubble
GOval oval = new GOval (100, 100, 50, 50);
oval.setFilled(true);
oval.setColor(Color.WHITE);
add(oval);

//randomly generate coordinates within the field


//add the bubble and pause


Thread.sleep(100);
}

您还不断添加 GOval 对象。我不知道 GraphicsProgram 类,但它也可能会导致您的内存在某些时候被填满。

关于java - 使对象在单击时出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995351/

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