简体   繁体   中英

Java Applet - Moving a ball over the screen

Ok, how to i move from keyboard a ball using an Applet?

I have so far this code, that don't do anything.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class KeyboardGame extends Applet implements KeyListener
{

    private static final long serialVersionUID = 1L;
    private static boolean keyboadrRightPressed = false;

    public void init()
    {
         addKeyListener(this);
    }

    public void keyPressed(KeyEvent e) 
    {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_RIGHT)
        {
            keyboadrRightPressed = true;
        }
        else
        {
            keyboadrRightPressed = false;
        }
    }

    public void keyReleased(KeyEvent e) {

    }

    public void keyTyped(KeyEvent e) {
    }

    public void paint(Graphics g)
    {
        g.fillOval(20,20,20,20);
        g.drawString("String :"+keyboadrRightPressed,20,30);
    }

}

And also i have to understand how it works. I don't get why my action listener won't work, do i need an

while(true)

or an Thread?

Your action listener might actually be working fine, but you need to repaint the applet when the key is pressed so that your string actually appears. Try changing the keyPressed to this:

public void keyPressed(KeyEvent e) 
{
    int keyCode = e.getKeyCode();
    if(keyCode == KeyEvent.VK_RIGHT)
    {
        keyboadrRightPressed = true;
    }
    else
    {
        keyboadrRightPressed = false;
    }
    repaint();
}

Actually moving the ball will differ depending on how you want the ball to actually move. I'm guessing you want it to continue moving right while the key is held down, so what I would do is implement a timer or some other form of thread that every .25 seconds (or however long you want) checks the keyboardRightPressed and will move the ball right if it is true. Then in the keyReleased portion of your code you should also add logic to set keyboardRightPressed back to false when you let up on the key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM