我需要知道如何在Thread启动后停止Java Graphics中的对象移动。通过更改指示形状的属性来完成动画。我试图在run()
上设置条件以使对象停止移动,但似乎它没有通过条件。
这是我将动画的对象的代码。
import java.awt.*;
import java.awt.geom.*;
public class House implements DrawingObject
{
private double x;
private double y;
private Color roofC;
private Color baseC;
private Triangle roof;
private Square base;
private double speed;
private double size;
public House(double a, double b, Color r, Color ba, double sz)
{
x = a;
y = b;
roofC = r;
baseC = ba;
size = sz;
roof = new Triangle(x, y, x + (size / 2), y + (size / 3), x - (size / 2), y + (size / 3), roofC);
base = new Square(x - (size / 2), y + (size / 3), size, baseC);
speed = -5;
}
public double getX()
{
return x;
}
public void stop()
{
speed = 0;
}
//these are the methods to be overridden when implementing DrawingObject
public void draw(Graphics2D g2d, AffineTransform at)
{
roof.draw(g2d, affn);
base.draw(g2d, affn);
}
public void animate()
{
roof.incX(speed);
base.incX(speed);
}
这是我绘制对象并调用其animate()
方法的代码。
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import javafx.scene.input.KeyCode;
public class DrawingComponent extends JComponent implements Runnable
{
private int width;
private int height;
private JFrame frame;
private boolean running;
private int delay;
private ArrayList<DrawingObject> dos = new ArrayList<DrawingObject>();
private MyKeyListener mkl;
private Graphics2D g2d;
private House h;
public DrawingComponent(JFrame f)
{
frame = f;
running = false;
delay = 100;
h = new House(640, 200, Color.RED, Color.WHITE, 100);
}
protected void paintComponent (Graphics g)
{
g2d = (Graphics2D) g;
AffineTransform reset = g2d.getTransform();
RenderingHints rh =
new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHints(rh);
//move to 250, 200
h.draw(g2d, reset);
dos.add(h);
}
public void activateKL()
{
mkl = new MyKeyListener();
frame.getContentPane().addKeyListener(mkl);
frame.getContentPane().setFocusable(true);
}
class MyKeyListener implements KeyListener
{
Thread t1 = new Thread(DrawingComponent.this);
public void keyTyped(KeyEvent e)
{
if(!running)
{
running = true;
t1.start();
}
}
public void keyPressed(KeyEvent e)
{
if(!running)
{
running = true;
t1.start();
}
}
public void keyReleased(KeyEvent e)
{
}
}
public void run()
{
while(running)
{
animateAll();
repaint();
try
{
Thread.sleep(delay);
}
catch (InterruptedException ex)
{
}
if(h.getX() <= 250)
{
h.stop();
}
}
}
public void animateAll()
{
for (int i = 0; i < dos.size(); i++)
{
dos.get(i).animate();
}
}
}
在DrawingComponent
方法中,有一个DrawingObject
的ArrayList,据说拥有该实现的所有对象。 animateAll()
调出ArrayList中每个DrawingObject
的所有动画。
所以我在这里使用了一种方法来改变以阻止House对象移动,但它仍然不起作用。我甚至尝试将条件if(h.getX() <= 250)
放在House
类中,甚至放在animateAll()
类中。我在代码中遗漏了什么吗?
PS:我需要执行此类程序,因此不会批准使用计时器或删除animateAll()
方法等建议。