当我点击两次三角形时,我试图为三角形设置动画。一旦我点击它们两次三角形0开始移动直到moveX达到20,而(moveX <20),但是它似乎没有达到终止状态,它不会进入内部:if(t.getState( )== Thread.State.TERMINATED),有什么想法吗?
public class secondFrame extends JFrame implements Runnable {
}
public secondFrame(ChallengesDialog dialog) {
component = new secFrameDrawComponent();
createComponent();
Thread t = new Thread(this);
t.start();
}
private void createComponent() {
sGen = new shapeGenerator(434, 231);
createT();
}
class AddComponentListener implements MouseListener {
public void mouseClicked(MouseEvent event) {
for(int i = 0; i < count; i++) {
if (component.getTri(i).contains(event.getX(), event.getY())) {
component.setShapeFill("triangle", i);
component.repaint();
countColors(i);
setChallenge();
}
...
MouseListener listener = new AddComponentListener();
component.addMouseListener(listener);
public void setChallenge() {
//two red triangles
if(challenge == 1 && triColorCount[1] == 2) {
Thread t = new Thread(component);
t.start();
System.out.println("Thread's state: " + t.getState());
if(t.getState() == Thread.State.TERMINATED) {
//Unreachable
System.out.println("Thread completed");
}
}
}
...
public void run() {
while(threadFlag) {
..
timeLabel.setText("Elapsed time: " + elapsedTime);
..
}
}
public class secFrameDrawComponent extends JComponent implements Runnable {
public void modTriangle(int x, int y) {
sGen.setTriangleOffset(x, y);
triangle[0] = sGen.getTriangle();
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
draw(g2);
}
public void run() {
while(moveX < 20) {
moveX+= 1;
modTriangle(moveX, 0);
repaint();
try {
Thread.sleep(170);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("moveX = " + moveX);
}
System.out.println("Thread completed exec");
}
public void draw(Graphics2D g2) {
g2.setStroke(new BasicStroke(2));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
modTriangle(moveX, 0);
g2.draw(triangle[0]);
g2.draw(triangle[1]);
}
答案 0 :(得分:1)
仔细看看你在做什么。您开始一个新线程,然后立即检查它是否已终止。当然它不会,它需要一段时间才能完成动画。如果要等到线程完成,请使用join()
功能。但请注意,这将阻止调用线程,直到您“加入”的线程结束。