gpt4 book ai didi

Java 输入不适用于 Canvas

转载 作者:行者123 更新时间:2023-12-02 07:39:23 31 4
gpt4 key购买 nike

我正在用 Java 编写一个基本程序。我让输入使用此代码:

package main;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;

public class Input extends KeyAdapter{
public void keyPressed(KeyEvent ke){
_press[ke.getKeyCode()] = true;
_pressed[ke.getKeyCode()] = true;
}
public void keyReleased(KeyEvent ke){
_press[ke.getKeyCode()] = false;
_released[ke.getKeyCode()] = true;
}
public void update(){
for (int i = 0; i < _press.length; i ++){
_pressed[i] = false;
_released[i] = false;
}
}
/**
* checks if a key is being pressed
* @param key an integer representing a key(Key class recommended)
* @return boolean
*/
public static boolean check(int key){
if (_press[key]) return true; else return false;
}
/**
* checks if a key was pressed
* @param key an integer representing a key(Key class recommended)
* @return boolean
*/
public static boolean pressed(int key){
if (_pressed[key]) return true; else return false;
}
/**
* checks if a key was released
* @param key an integer representing a key(Key class recommended)
* @return boolean
*/
public static boolean released(int key){
if (_released[key]) return true; else return false;
}
protected static boolean[] _press = new boolean[128];
protected static boolean[] _pressed = new boolean[128];
protected static boolean[] _released = new boolean[128];
}

我运行了测试,我得到了一个使用 ArrayList 运行的基本实体系统,一切都很好。

但后来我遇到了图形问题。

我设置了一个 Jcanvas 类(扩展 Canvas),但是将其添加到我的框架中后,图形将正常工作,但我的输入根本不再起作用。

canvas = new Jcanvas();
canvas.setSize(width, height);
canvas.setBackground(Color.RED);
frame.add(canvas);

//input
frame.addKeyListener(new Input());

有没有办法解决这个问题,或者我会被图形或输入卡住吗?

这是我的 Jcanvas 类供引用:

package main;
import java.awt.Canvas;
import java.awt.Graphics;

public class Jcanvas extends Canvas{
static final long serialVersionUID = 42L;
public void paint(Graphics g){
}
public void drawrect(int x, int y, int width, int height){
Graphics g = getGraphics();
//g.setColor(Color.blue);
g.drawRect(x, y, width, height);
}
public void drawfill(Graphics g, int x, int y, int width, int height){
}
}

最佳答案

尝试添加:

//input
Input input = new Input();
frame.addKeyListener(input);
canvas.addKeyListener(input);

关于Java 输入不适用于 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11786026/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com