通过使用paintComponent进行简单动画

时间:2014-03-09 05:23:13

标签: animation paintcomponent repaint

我正试图在面板顶部做一个小方块移动。我并不担心动画或闪烁的无缝性或类似的东西。似乎在while循环中,repaint()不会重复调用paintComponent。想法?

公共类NodeMove扩展了JFrame {

boolean running = true;

public NodeMove() {

    widgetNode panel = new widgetNode();
    add(panel);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 400);
    setVisible(true);

    Runnable node = new widgetNode();
    Thread thread1 = new Thread(node);
    thread1.start();
}

class widgetNode extends JPanel implements Runnable {

    private static final long serialVersionUID = 1L;    
    private int x = 30;
    private int y = 30;     
    public widgetNode() {
    }

    public void run(){

        while(running){
            nodeUpdate();
            repaint();

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {}
        }
    }

    public void nodeUpdate(){
        x += 4;
    }

    protected void paintComponent(Graphics g) {
        super.paintComponents(g);
        g.drawRect(x, y, 30, 30);
    }
}

public static void main(String[] args) {

    NodeMove frame = new NodeMove();
    for(int i = 0; i < 50; i++){
        frame.repaint();
    }
}

}

0 个答案:

没有答案