1

I need to draw a rectange,circle and line and then animate them(press left -> it(all objects) moves left for examp.)

I draw objects like this

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);
  }
}

But it doesn't move.

lapots
  • 12,553
  • 32
  • 121
  • 242

1 Answers1

2
  1. use paintComponent(Graphics g) for Swing JComponents instead of paint(Graphics g)

  2. use KeyBindings for KeyEvents for Swing JComponents

  3. put Objects (prepare before paintComponent(Graphics g)) to the Array, paint elements from Array in paintComponent(Graphics g)

mKorbel
  • 109,525
  • 20
  • 134
  • 319