KeyListener on不起作用:Java

时间:2014-09-28 01:00:12

标签: java keylistener

我写了一些代码在屏幕上创建一个小方块,但是当我按下左键时,似乎什么都没发生。矩形不移动,"向左移动。"没有在控制台中打印出来。这是代码。

package game;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings({ "serial" })
public class Game extends Canvas implements Runnable, KeyListener{

    public static final int WIDTH = 400;
    public static final int HEIGHT = WIDTH/12 * 9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";
    //Size, scale, and name of window.

    boolean running = false;
    public int tickCount = 0;

    //X and Y coordinates of the rectangle on the screen.
    private static int rectX = 10;
    private int rectY = 10;

    JFrame f;
    Canvas can;
    BufferStrategy bs;

    Controls c;
public Game(){

    f = new JFrame(NAME);
    f.setSize(400, 400);
    f.setVisible(true);
    //Sets the size of the window and makes it visible.
    JPanel panel = (JPanel) f.getContentPane();
    panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    panel.setLayout(null);
    //Sets preferred size and layout to null.
    can = new Canvas();
    can.setBounds(0, 0, 400, 400);
    can.setIgnoreRepaint(true);
    //Creates new canvas.
    panel.add(can);
     //Adds the canvas to the JPanel.
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setResizable(false);
    //Makes the window packed, nonresizable, and close the program on exit.
    can.createBufferStrategy(3);
    bs = can.getBufferStrategy();
    //Creates buffer strategy for the canvas.
    System.out.println("Window created.");
    addKeyListener(this);
}

public synchronized void start(){
    running = true;
    new Thread(this).start();
    //Starts thread
}

public synchronized void stop(){
    running = false;
    //For stopping the program.
}

public void run() {
    long lastTime = System.nanoTime();
    double nsPerTick = 1000000000.0/60.0;

    int frames = 0;
    int ticks = 0;
    long lastTimer = System.currentTimeMillis();
    double delta = 0;
    while(running)
    {
        long now = System.nanoTime();
        delta += (now - lastTime)/nsPerTick;
        lastTime = now;
        boolean shouldRender = true;
        while(delta>=1)
        {
        ticks++;
        tick();
        delta -= 1;
        shouldRender = true;
        //Creates 60fps timer. Not in use.
        }
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(shouldRender)
        {
        frames++;
        render();
        //Renders the image.
        }
        if(System.currentTimeMillis() - lastTimer >= 1000)
        {
            lastTimer += 1000;
            System.out.println(frames + " frames, " + ticks + " ticks");
            frames = 0;
            ticks = 0;
            //Resets timer. Not in use.
        }
    }
}

public void tick(){
    tickCount++;
    //Not in use, yet.
}

public void render(){
    Graphics2D g = (Graphics2D)bs.getDrawGraphics();
    //Sets g to the buffer strategy bs.
    g.setColor(Color.BLACK);
    g.fillRect(rectX, rectY, 100, 100);
    //Creates black rectangle.
    g.dispose();
    bs.show();
    //Puts the rectangle on the screen.
}

public static void main(String [] args){
    new Game().start();
    //Starts thread.
}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {
    if(e.getKeyCode()==KeyEvent.VK_LEFT)
    {
        --rectX;
        System.out.println("Move left.");
    }

}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

}

1 个答案:

答案 0 :(得分:0)

因为在你的构造函数中,你创建了一个新的Canvas,并且没有使用Game画布,你的矩形是在新的Canvas上绘制的,而不是Game canvas,所以你的听众没有效果。

请看下面的新构造函数,我测试过,它工作正常。

    public Game() {

        frame = new JFrame(NAME);
        frame.setSize(400, 400);
        frame.setVisible(true);
        // Sets the size of the window and makes it visible.
        JPanel panel = (JPanel) frame.getContentPane();
        panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        panel.setLayout(null);
        // Sets preferred size and layout to null.
        //can = new Canvas();
        //can.setBounds(0, 0, 400, 400);
        //can.setIgnoreRepaint(true);
        setBounds(0, 0, 400, 400);
        setIgnoreRepaint(true);
        // Creates new canvas.
        panel.add(this);
        // Adds the canvas to the JPanel.
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        // Makes the window packed, nonresizable, and close the program on exit.
        //can.createBufferStrategy(3);
        createBufferStrategy(3);
        bs = getBufferStrategy();
        // Creates buffer strategy for the canvas.
        System.out.println("Window created.");
        addKeyListener(this);
    }