Java Key Listener,Key adapter,Key Pressed()无效

时间:2016-09-17 22:29:17

标签: java keylistener

我试图将addkeylistener方法放入cubegame类中,但这仍然无效。 cubegame是jframe并响应窗口侦听器事件。 cubegamepanel是一个jpanel,有一个运行游戏的线程。

package CubeGame;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.input.KeyCode;

public class CubeGame extends JFrame implements WindowListener{

private static int PWIDTH = 400;
private static int PHEIGHT = 400;
private CubeGamePanel cgp;

public volatile boolean left = false;
JLabel fps;
JLabel ups;

public CubeGame(){
    super("CubeGame");
    //super.setPreferredSize(new Dimension(PWIDTH, PHEIGHT));
    setSize(PWIDTH, PHEIGHT);
    addWindowListener(this);

    makeGUI();

    setVisible(true);


}

private void makeGUI(){
    fps = new JLabel("Waiting for Input...");
    ups = new JLabel("Waiting for Input...");

    JPanel southPanel = new JPanel();
    cgp = new CubeGamePanel(this);
    JPanel centerPanel = cgp;

    //southPanel.add(new JSeparator(SwingConstants.VERTICAL), BorderLayout.NORTH);
    southPanel.add(fps);
    southPanel.add(ups);

    add(southPanel, BorderLayout.SOUTH);
    add(centerPanel, BorderLayout.CENTER);

}

public static void main(String[] args){
    CubeGame cg = new CubeGame();
}

@Override
public void windowOpened(WindowEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void windowClosing(WindowEvent e) {
    System.exit(0);
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void windowClosed(WindowEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void windowIconified(WindowEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void windowDeiconified(WindowEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void windowActivated(WindowEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void windowDeactivated(WindowEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

}

cubegamepanel类:

/*
* To change this license header, choose License Headers in Project           Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package CubeGame;

import com.sun.j3d.utils.timer.J3DTimer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.j3d.utils.*;

/**
*
* @author Morgan Higginbotham
*/
public class CubeGamePanel extends JPanel implements Runnable{

private CubeGame cg;

private int cubeWidth = 50;
private int cubeHeight = 50;
private volatile float cubeX = 0;
private volatile float cubeY = 0;
private float cubeMoveInterval = 0.02f;

private static final int NO_DELAYS_PER_YEILD = 16;
private static final int MAX_FRAME_SKIPS = 5;
private final int defaultFPS = 80;
public volatile float period = 1000/defaultFPS;
public static final int PWIDTH = 400;
public static final int PHEIGHT = 400;

private Thread animator;

private volatile boolean running = false;
private volatile boolean gameOver = false;
private volatile boolean isPaused = false;

private Image image = null;
private Graphics graphics = null; 

public CubeGamePanel(CubeGame cg){
    this.cg = cg;

    setFocusable(true);
    requestFocus();
    addKeyListener( new KeyAdapter() {
// listen for esc, q, end, ctrl-c on the canvas to
// allow a convenient exit from the full screen configuration
    public void keyPressed(KeyEvent e)
       { int keyCode = e.getKeyCode();
            if (e.getKeyCode() == KeyEvent.VK_D){
                System.out.println("hi");
                cg.left = false;
            }
            else if (e.getKeyCode() == KeyEvent.VK_A){
                cg.left = true;
            }
        }
    });
}

public void paintComponent(Graphics g){
    super.paintComponents(g);
    if (image != null){
        g.drawImage(image, 0, 0, null);
    }
}

@Override
public void run() {
    long beforeTime, afterTime, timeDiff, sleepTime, overSleepTime, excess;

    excess = 0L;
    overSleepTime = 0L;
    int noDelays = 0;

    beforeTime = J3DTimer.getValue();

    running = true;
    while(running){
        gameUpdate();
        gameRender();
        paintScreen();

        afterTime = J3DTimer.getValue();
        timeDiff = afterTime - beforeTime;
        sleepTime = (long) ((period - timeDiff) - overSleepTime);

        if (sleepTime > 0){
            try {
            Thread.sleep(sleepTime/1000000L);
            } catch (InterruptedException ex) {
               Logger.getLogger(CubeGamePanel.class.getName()).log(Level.SEVERE, null, ex);
            }
            excess -= sleepTime;
            overSleepTime = (J3DTimer.getValue()- afterTime) - sleepTime;
        }
        else{
            overSleepTime = 0L;

            if (++noDelays >= NO_DELAYS_PER_YEILD){
                Thread.yield();
                noDelays = 0;
            }
        }

        beforeTime = J3DTimer.getValue();

        int skips = 0;
        while((excess > period) && (skips < MAX_FRAME_SKIPS)){
            excess -= period;
            gameUpdate();
            skips++;
        }
    }
    System.exit(0);
}

public void addNotify(){
    super.addNotify();
    startGame();
}

private void startGame(){
    if (animator == null || !running){
        animator = new Thread(this);
        animator.start();
    }
}

public void stopGame(){
    running = false;
}

private void gameUpdate(){
    if (!gameOver){
        moveCube();
    }
}

private void paintScreen(){
    Graphics g;
    try{
        g = this.getGraphics();

        if ((g != null) && (image != null)){
            g.drawImage(image, 0, 0, null);
        }

        Toolkit.getDefaultToolkit().sync();
        g.dispose(); 
    }
    catch (Exception e){
        System.out.println("Graphics Contenet Error: " + e);
    }
}

private void moveCube(){
    if (cg.left){
        cubeX -= cubeMoveInterval;
        cubeY -= cubeMoveInterval;
    }
    else{
        cubeX += cubeMoveInterval;
        cubeY += cubeMoveInterval;
    }
}

private void gameRender(){
    if (image == null){
        image = createImage(PWIDTH, PHEIGHT);
        if (image == null){
            System.out.println("Image is null");
        }
        else{
            graphics = image.getGraphics();
        }
    }

    graphics.setColor(Color.white);
    graphics.fillRect(0, 0, PWIDTH, PHEIGHT);

    graphics.setColor(Color.RED);
    graphics.fillRect((int) cubeX, (int) cubeY, cubeWidth, cubeHeight);

}

}

0 个答案:

没有答案