keylistener和runnable不工作

时间:2013-11-26 02:47:26

标签: java keylistener runnable

你能看到问题吗?线程运行正常,但砖不想响应密钥监听器。我尝试测试keylistener是否最终获得了一个事件,但它甚至没有system.out.println

import java.awt.*;//imports
import java.util.*;
import java.applet.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class Start extends Applet implements Runnable, KeyListener// where i put the keylistener in
{

    DrawBackground dbg = new DrawBackground();
    Brick brick = new Brick();
    Thread gameLoop;

    public void init() {
        addKeyListener(this);// i add the key listener
    }

    public void start() {
        Thread gameLoop = new Thread(this);
        gameLoop.start();
    }

    public void run() {
        while (true) {

            brick.update(1);
            repaint();
            try {
                Thread.sleep(17);
            }
            catch (InterruptedException e) {
            }

        }
    }

    public void stop() {

    }

    public void paint(Graphics g)// with out any paint it works if im changing
                                 // somthing like a lable
    {
        dbg.paint(g, this);
        brick.paint(g, this);
    }

    public void keyPressed(KeyEvent e)// test to see if it works
    {
        System.out.println("why");
        if (e.getKeyCode() == 37) {
            brick.left();
        }
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {

    }
}

这是Brick类我想要移动的东西

import java.awt.*;
import java.util.*;
import java.applet.*;

public class Brick {

    public int dy = 40;
    public int yStart = -20;
    public int time = 0;
    public int dx = 0;
    public int xStart = 0;
    public int start = 1;

    public void paint(Graphics g, Start sp) {
        Dimension screenSize = sp.getSize();
        int sheight = screenSize.height;
        int swidth = screenSize.width;
        if (start == 1) {
            xStart = swidth - (int) (swidth / 2.5);
            start = 0;
        }
        int bWidth = swidth / 15;
        int bHeight = swidth / 15;
        int time = 0;
        g.setColor(Color.red);
        g.fillRect(xStart, yStart, bWidth, bHeight);
    }

    public void update(int x) {
        if (time == 60) {
            time = 0;
            yStart += dy;
        }
        else {
            time += x;
        }
    }

    public void left() {
        xStart -= dx;
    }
}

1 个答案:

答案 0 :(得分:1)

看起来您没有设置键盘焦点。见this question.

我在添加keyListener之后总是使用setFocusable(true)并且它为我工作,但是这个问题的答案有更好的解决方案。