我已经编写了一些关于移动图形(被矩形包围)的代码,并且我正在尝试绘制另一个随机生成的椭圆形(周围有一个矩形)。现在,它的生成速度非常快,而且我不想使用 Thread.sleep;因为它会停止监听按键(据我所知?)。那么,任何精通多线程的人都可以帮助我做到这一点,或者知道如何使图形显示出来,直到它被可移动图形触摸为止。
主类中的图形生成器:
public void paintComponent(Graphics g){
//System.out.println("X = " + al.x + ", Y = " + al.y);
boolean intersect = false;
int points = 0;
g.drawString("Points: " + points, 5, 445);
Rectangle r1 = new Rectangle(al.x, al.y, 10, 10);
g.setColor(Color.BLACK);
g.fillOval(al.x, al.y, 10, 10);
Random randX = new Random();
Random randY = new Random();
int xInt = randX.nextInt(590);
int yInt = randY.nextInt(440);
Rectangle dCoin = new Rectangle(xInt, yInt, 10, 10);
g.setColor(Color.YELLOW);
g.fillOval(xInt, yInt, 10, 10);
/*
* (???)
*
* for(int idx = 1; idx == 1; idx++){
* if(xInt < 590 && yInt < 440){
* }
* }
*
* Check if graphic collides with another:
*
* if(r1.intersects(r2)){
* doSomething;
* }
*
*/
repaint();
}
}
顺便说一句:r1 围绕可移动图形,r2 是围绕随机生成图形的矩形。我必须在椭圆周围制作不可见的矩形才能获得 r1.intersects(r2) 方法。
最佳答案
您应该使用 Swing Timer
定期生成 ActionEvent
的类事件调度线程上的 s。这可以避免应用程序对击键和其他用户输入无响应的问题。
actionPerformed
回调是您的路由的 Hook ,用于移动和重新绘制您想要设置动画的对象。在动画例程中,您可以记录自上次调用该方法以来耗时,以保持所需的速度。
Timer timer = new Timer(1000, new ActionListener() {
long lastTime = System.currentTimeMillis();
public void actionPerformed(ActionEvent evt) {
long timeNow = System.currentTimeMillis();
long timeEllapsed = timeNow - lastTime;
lastTime = timeNow;
if (timeEllapsed > 0L) {
for (Moveable mv : moveables) {
mv.updatePosition(timeEllapsed);
}
for (Drawable d : drawables) {
d.repaint();
}
}
}
});
关于java - 如何使图形随机出现并在与另一个图形碰撞时消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7845920/