gpt4 book ai didi

java - 如何多次创建对象以在屏幕上同时移动?

转载 作者:行者123 更新时间:2023-11-29 03:51:45 24 4
gpt4 key购买 nike

我有一个线程在 y 方向下落一个圆圈。我现在想在屏幕上同时使用随机 x 位置创建几个圆圈。

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Goo
{
protected GooPanel gooPanel;
private boolean loop = true;
protected int width , height;
private int frameTimeInMillis = 50;
private RenderingHints renderingHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING , RenderingHints.
VALUE_ANTIALIAS_ON);
@SuppressWarnings("serial")

class GooPanel extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHints(renderingHints);
draw(g2d);
}
}

public Goo()
{
this (800, 500);
}

public Goo(int w, int h)
{
width = w;
height = h;
JFrame frame = new JFrame ();

frame.setSize(width , height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gooPanel = new GooPanel ();
gooPanel.setPreferredSize(new Dimension(w, h));
frame.getContentPane ().add(gooPanel);
frame.pack();
frame.setVisible(true);
}

public void go()
{
while (loop)
{
gooPanel.repaint();
try
{
Thread.sleep(frameTimeInMillis);
} catch (InterruptedException e) {}
}
}

public void draw(Graphics2D g) {}

public void setFrameTime(int millis)
{
frameTimeInMillis = millis;
}

public Component getGooPanel ()
{
return gooPanel;
}
}

我的 FallingDrop 类:

import java.awt.*;

public class FallingDrops extends Goo
{
double x, y, r;
int red, green, blue = 0;
Color a;

FallingDrops()
{
x = width / 2;
r = 10;
y = -r;
}

FallingDrops(double x)
{
this.x = x;
r = 10;
y = -r;
}

public void draw(Graphics2D g)
{
g.setColor(Color.GRAY);
g.fillRect(0, 0, width , height);
g.setColor(Color.WHITE);

g.fillOval ((int) (x - r), (int) (y - r), (int) (2 * r),
(int) (2 * r));

y++;
if (y - r > height)
y = -r;

}


public static void main(String [] args)
{
int num = 10;
Goo gooDrop [] = new FallingDrops[num];

for(int i = 0; i < gooDrop.length; i++)
{
double x = Math.random()*800;
gooDrop[i] = new FallingDrops(x);
System.out.println(x);
gooDrop[i].go();
}

}


}

目前go()方法执行时,循环无法完成;因此只在屏幕上绘制一个对象,而不是我循环中指示的多个对象。我确信这是一个简单的修复。知道我做错了什么吗?

最佳答案

go() 方法永远不会返回。当它在数组中的第一个对象上被调用时,它会无限地继续工作。您应该在一个不断重新绘制的单独线程中进行重新绘制。或者,如果您只想在添加水滴时重绘,请在您的 go 方法中删除 while

public void go() 
{

gooPanel.repaint();
try
{
Thread.sleep(frameTimeInMillis);
} catch (InterruptedException e) {}

}

这样它会在重新绘制和暂停后返回。

关于java - 如何多次创建对象以在屏幕上同时移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8444239/

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