我需要绘制一个矩形,圆形和直线然后为它们设置动画(按左 - >>它(所有对象)向左移动以进行示例。)
我画这样的对象
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);
}
}
但它没有动。
答案 0 :(得分:2)
使用paintComponent(Graphics g)
进行Swing JComponents
而不是paint(Graphics g)
KeyBindings
使用KeyEvents
进行Swing JComponents
将对象(在paintComponent(Graphics g)
之前准备)放到数组中,在paintComponent(Graphics g)