gpt4 book ai didi

java - KeyAdapter 在 JPanel 类中不起作用,但在 JFrame 类中起作用

转载 作者:搜寻专家 更新时间:2023-11-01 02:29:03 24 4
gpt4 key购买 nike

背景
我正在构建一个游戏库以加快游戏开发速度,到目前为止进展相当顺利。

我有以下内容:

  • 主入口类public static void main(String[] args)
    • 这个类然后从我的库中启动一个名为 Game
    • 的类
    • 然后设置窗口大小并添加一个RoomJFrame
  • 当一个可扩展的房间(房间是一个游戏关卡)类被创建时,它会从房间启动一个线程来绘制添加到它的所有对象。
    • 对象可以添加事件(我坚持的部分)

以上就是主要思想所包含的内容。

这里是入口类(很简单)。

package test;

import JGame.Game.Game;
import JGame.Room.Room;
import javax.swing.JFrame;
import test.Rooms.Room1;

public class Main extends JFrame{

public static void main(String[] args){
Game game = new Game("Test Game"); // This sets the window title
game.start(800, 600); // This sets the size of the window

Room room1 = new Room1();
game.setRoom(room1); // adds the JPanel to the main frame
}
}

Room1 扩展 Room。在 Room1 中,所有与该房间关联的游戏对象都添加到其中。

public class Room extends JPanel implements Runnable{
ArrayList<GameObject> gameObjects = new ArrayList<>();
@Override
public void run(){
try{
while(true){
this.repaint();
Thread.sleep(5);
}
}
}
public void addGameObjectAt(GameObject gameObject, int x, int y){
// Sets private variables in GameObject
// These are then grabbed in the paintComponent to draw at that location
gameObject.setX(x);
gameObject.setY(y);
gameObjects.add(gameObject);
}
@Override
public void paintComponent(Graphics g){
g.drawImage(bg, 0, 0, this);
for(int i = 0; i < gameObjects.size(); i++){
GameObject go = gameObjects.get(i);
g.drawImage(go.getSprite(), go.getX(), go.getY(), this);
}
}
}

假设我们创建了一个房间:

public class Room1 extends Room{
public Room1(){
this.createShip();
}
public void createShip(){
Ship = new Ship();
// Add an object to a list setting its x,y to 10,10
this.addGameObjectAt(ship, 10, 10);
}
}

注意:这些对象不会通过 addGameObjectAt 添加到窗口中,它们只是添加到 ArrayList 中,然后添加到 Room 中的线程中被绘制到屏幕上。

现在我们已将 Ship 添加到房间,可以使用 paintComponent() 在屏幕上绘制它。这一切都很好!

这里是事情开始停止工作的地方。现在我们添加了一个 Ship 类,我想添加一些关键事件,目前我必须添加 Main 才能使它们工作,但我不想将它们添加到那里,因为它变得困惑,我想将它们添加到 Ship,因为这是事件最终会产生的影响。

这段代码没有附加keylistener

// GameObject extends JPanel
public class Ship extends GameObject{
public Ship(){
this.addKeyListener(new AL());
}

public class AL extends KeyAdapter{

@Override
public void keyPressed(KeyEvent evt){
System.out.println("here");
}

@Override
public void keyReleased(KeyEvent evt){
}
}
}

这不起作用,按一个键不会在这里打印出来,但是如果我移动 AL 类和 addKeyListener()Game 类它可以工作,但我不希望它出现在 Game 类中我希望它出现在 Ship 类中。

// This class just sets up the size of the application window
// It also holds an int list of all the game rooms
public class Game extends JFrame{

}

至少一个星期以来,我一直在努力解决这个问题,但我似乎无法弄清楚如何才能让它在 Ship 类中工作?

最佳答案

JPanel 不是可聚焦组件,因此无法与 KeyEvents 交互。

在 Swing 中,首选方法是使用 Key Bindings .即使组件没有焦点,您也可以将 Action 映射到 KeyStroke。

查看此 example

关于java - KeyAdapter 在 JPanel 类中不起作用,但在 JFrame 类中起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13995458/

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