我的代码

时间:2016-10-15 15:54:41

标签: java swing timer

所以我正在制定的计划的计划是让一个物体从一个点移动到另一个点。捕获的是绘制路径。我可以绘制并放置shape从头到尾穿过路径。我遇到的问题是该对象出现在路径的末尾。即使在timer的末尾设置了for loop也是如此。它所做的只是等待timer完成,然后形状就在路径的尽头。

我已经完成了代码,甚至打印出了已存储的每个点,我得到了积分,而不仅仅是最后一点。对象的路径基于穿过每个点并将对象放置在所述点的for循环。它是粗糙的atm并使用绝对位置(仅适用于对象)。

我错过了什么?

以下是代码:

    JButton add = new JButton("add");
    add(add);
    //new Timer(50, updateTask).start();
    updateTask = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            repaint();  // Refresh the JFrame, callback paintComponent()
        }
     };

    add.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            for (int i = 0; i < path.size(); i++) {
                update(i);   // update the (x, y) position
                new Timer(1000, updateTask).start();
            }
        }
    });
}

public void update(int i) {
    if (released == 1) {
        Point p = path.get(i);
        System.out.println("position at: " + (int) p.getX() + " " + (int) p.getY());
        xPos = (int) p.getX();
        yPos = (int) p.getY();
        System.out.println(i);
    } 
}

1 个答案:

答案 0 :(得分:3)

You can't write your loop within an ActionListener, since that would block the EventDispatchThread (EDT) and therefore block your UI.

Instead you can use the updateTask ActionListener to step through your path each time it is called from the Timer:

final Timer timer = new Timer(1000, null);
updateTask = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent evt) {
        if (pathIndex < path.size()) {
            update(pathIndex++);
        } else {
            timer.stop();
        }
        repaint();  // Refresh the JFrame, callback paintComponent()
    }
};
timer.addActionListener(updateTask);

add.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        pathIndex = 0;
        timer.start();
    }
});

For this to work your class needs an additional int field pathIndex

相关问题