0

当两个三角形被单击两次时,我正在尝试为三角形设置动画。一旦我单击它们两次三角形 0 开始移动,直到 moveX 达到 20,while(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]);
    }
4

1 回答 1

1

仔细看看你在做什么。您启动一个新线程,然后立即检查它是否已终止。当然不会,动画完成需要一段时间。如果要等到线程完成,请使用该join()函数。但是请注意,这将阻塞调用线程,直到您“加入”的线程完成。

于 2012-09-03T14:29:36.843 回答