0

Hey guys, I'm new here and a n00b in Java, trying to figure things out though :)

I want to make a polygon move in a Java Applet but I keep struggling with the keylistener (aka it doesn't do anything) Maybe someone can help me please?

Here's my code:
(I'll just post the more important parts, I think they may be something I'm forgetting in here...)

public void init() {
       	bi = (BufferedImage)createImage(getSize().width,getSize().height);
        big = (Graphics2D)bi.getGraphics();

	setBackground(Color.blue);
	setForeground(Color.yellow);

        for (int i = 0; i < 5; i++){
	      volfie.addPoint((int) (350 + 20 * Math.cos(i * 2 * Math.PI / 5)),
	          (int) (350 + 20 * Math.sin(i * 2 * Math.PI / 5 )));
        }

	addKeyListener(this);
	setFocusable(true);

		for (int i = 0; i < 5; i++){
	          xpoints[i] = (int)(350 + 20 * Math.cos(i * 2 * Math.PI / 5));
	          ypoints[i] = (int)(350 + 20 * Math.sin(i * 2 * Math.PI / 5 ));
		}

	animation = new Thread(this);
    	animation.start();
	}
public void run()
	{
	  	while(true)
	  	{
		if(upKey){ moveUp(); }
                if(downKey){ moveDown(); }
                if(leftKey){ moveLeft(); }
                if(rightKey){ moveRight(); }
	  		try
	      	{
	        	animation.sleep(100);


	        	repaint();
	      	}
	      	catch(Exception e) {}
	  	}
   }
public void keyPressed(KeyEvent e){
            switch (e.getKeyCode()){
                case KeyEvent.VK_LEFT:
                leftKey = true;
                break;
                case KeyEvent.VK_RIGHT:
                rightKey = true;
                break;
                case KeyEvent.VK_UP:
                upKey = true;
                break;
                case KeyEvent.VK_DOWN:
                downKey = true;
                break;
            }
        }
   public void keyReleased(KeyEvent e){
            switch (e.getKeyCode()){
                case KeyEvent.VK_LEFT:
                leftKey = false;
                break;
                case KeyEvent.VK_RIGHT:
                rightKey = false;
                break;
                case KeyEvent.VK_UP:
                upKey = false;
                break;
                case KeyEvent.VK_DOWN:
                downKey = false;
                break;
            }
        }

I figured it out, seems like the problem is with the move functions :)

Edited by v30: n/a

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by apines
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.