动画3对象

时间:2012-06-11 20:04:36

标签: java swing

我需要绘制一个矩形,圆形和直线然后为它们设置动画(按左 - >>它(所有对象)向左移动以进行示例。)

我画这样的对象

class MyCanvas extends JComponent {

int x = 10;
int y = 10;
public MyCanvas()
{
    Action someaction = new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            x+=30;
            //revalidate();
            repaint();
        }
    };
    this.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), someaction);
}        
@Override
public void paintComponent(Graphics g) {
g.drawRect(x,y, 200, 200); 
g.drawOval(x, y, 50, 50);
g.drawLine(x, y, 50, 30);
  }
}

但它没有动。

1 个答案:

答案 0 :(得分:2)

  1. 使用paintComponent(Graphics g)进行Swing JComponents而不是paint(Graphics g)

  2. KeyBindings使用KeyEvents进行Swing JComponents

  3. 将对象(在paintComponent(Graphics g)之前准备)放到数组中,在paintComponent(Graphics g)

  4. 中绘制数组中的元素