Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java密钥侦听器、密钥适配器、按键()不工作_Java_Keylistener - Fatal编程技术网

Java密钥侦听器、密钥适配器、按键()不工作

Java密钥侦听器、密钥适配器、按键()不工作,java,keylistener,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

我曾尝试将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);

}
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
包装盒;
导入com.sun.j3d.utils.timer.J3DTimer;
导入javax.swing.*;
导入java.awt.*;
导入java.awt.event.*;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入com.sun.j3d.utils。*;
/**
*
*@作者摩根·希金波坦
*/
公共类CubeGamePanel扩展了JPanel实现Runnable{
私人CubeGame cg;
私有整数立方宽度=50;
私有整数立方高度=50;
私有易失浮动cubeX=0;
私有浮动库比=0;
私有浮动立方体间隔=0.02f;
私有静态最终整数无延迟每夜=16;
私有静态最终整数最大帧跳过=5;
私人最终int defaultFPS=80;
公共浮动周期=1000/默认fps;
公共静态最终int PWIDTH=400;
公共静态最终int PHEIGHT=400;
私有线程动画师;
private volatile boolean running=false;
私有易失性布尔gameOver=false;
private volatile boolean isPaused=false;
私有图像=空;
私有图形=空;
公共CubeGame面板(CubeGame cg){
this.cg=cg;
设置聚焦(真);
requestFocus();
addKeyListener(新的KeyAdapter(){
//在画布上聆听esc、q、end和ctrl-c以
//允许方便地退出全屏配置
按下公共无效键(按键事件e)
{int keyCode=e.getKeyCode();
如果(例如getKeyCode()==KeyEvent.VK_D){
System.out.println(“hi”);
cg.left=假;
}
else if(e.getKeyCode()==KeyEvent.VK_A){
cg.left=true;
}
}
});
}
公共组件(图形g){
超级组件(g);
如果(图像!=null){
g、 drawImage(image,0,0,null);
}
}
@凌驾
公开募捐{
很久以前,以后,时差,睡眠时间,过度睡眠时间,过度;
过量=0升;
过睡眠时间=0L;
int节点延迟=0;
beforeTime=J3DTimer.getValue();
运行=真;
(跑步时){
gameUpdate();
gameRender();
漆幕();
afterTime=J3DTimer.getValue();
timeDiff=后时间-前时间;
睡眠时间=(长)((周期-时间差)-睡眠过度时间);
如果(睡眠时间>0){
试一试{
线程睡眠(睡眠时间/100000ml);
}捕获(中断异常例外){
Logger.getLogger(CubeGamePanel.class.getName()).log(Level.SEVERE,null,ex);
}
过量-=睡眠时间;
overSleepTime=(J3DTimer.getValue()-afterTime)-睡眠时间;
}
否则{
过睡眠时间=0L;
如果(++noDelays>=无延迟/每延迟){
螺纹屈服强度();
节点延迟=0;
}
}
beforeTime=J3DTimer.getValue();
int-skips=0;
而((超出>周期)和&(跳过<最大帧跳过)){
超额-=期间;
gameUpdate();
跳过++;
}
}
系统出口(0);
}
public void addNotify(){
super.addNotify();
startGame();
}
私有void startGame(){
如果(animator==null | |!正在运行){
animator=新线程(此);
animator.start();
}
}
公共游戏{
运行=错误;
}
私有void gameUpdate(){
如果(!gameOver){
moveCube();
}
}
私有虚空漆幕(){
图形g;
试一试{
g=this.getGraphics();
如果((g!=null)和&(image!=null)){
g、 drawImage(image,0,0,null);
}
getDefaultToolkit().sync();
g、 处置();
}
捕获(例外e){
System.out.println(“图形内容错误:+e”);
}
}
私有void moveCube(){
如果(重心左){
cubeX-=cubeMoveInterval;
cubeY-=cubeMoveInterval;
}
否则{
cubeX+=cubeMoveInterval;
cubeY+=cubeMoveInterval;
}
}
私有void gameRender(){
if(image==null){
图像=创建图像(PWIDTH,PHEIGHT);
if(image==null){
System.out.println(“图像为空”);
}
否则{
graphics=image.getGraphics();
}
}
图形.设置颜色(颜色.白色);
图形.fillRect(0,0,PWIDTH,PHEIGHT);
图形.设置颜色(颜色.红色);
图形.fillRect((int)cubeX,(int)cubeY,cubeWidth,cubeHeight);
}
}