gpt4 book ai didi

java - 如何同时运行ActionListener和KeyListener?

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:31 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的游戏,但由于某种原因,当我尝试使用 KeyPressed 方法时没有任何反应。我尝试了一些方法,发现错误是当我键入内容时程序永远不会进入 keyPressed 方法。我可以更改什么以使程序进入 keyPressed 方法?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Game extends JFrame {
public static void main(String[] args) {
Game maze = new Game();
maze.run();
}

public void run() {
JFrame frame = new JFrame("Game");
frame.setSize(800, 600);
frame.setLocation(50, 50);
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.setResizable(true);
GamePanel accessF = new GamePanel();
frame.setContentPane(accessF);
frame.setFocusable(true);
frame.setVisible(true);
}
}

class GamePanel extends JPanel {

int xDino, velX, velPlayerX, velPlayerY, xPlayer, yPlayer, code, code2;

public GamePanel() {
Timer tmD = new Timer(100, new DinoHandler());
tmD.start();
xDino = -800;
velX = 2;
velPlayerX = 0;
velPlayerY = 0;
xPlayer = 50;
yPlayer = 50;
KeyHandler ship = new KeyHandler();
addKeyListener(ship);
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.WHITE);
Image space = new ImageIcon("simple-star-space-background-effect-footage-023768280_prevstill.jpg").getImage();
g.drawImage(space, xDino, 0, 1600, 600, null);
if (xDino == 0) xDino = -800;

g.setColor(Color.GRAY);

g.fillRect(xPlayer, yPlayer, 50, 50);
}

class DinoHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
xDino = xDino + velX;
System.out.print(xDino);
repaint();
}
}

class KeyHandler implements KeyListener {
public void keyPressed(KeyEvent e) {
requestFocus();
xDino = 100;
code = e.getKeyCode();
if (e.getKeyCode() == KeyEvent.VK_UP) {
xPlayer = 60;
velPlayerY = 2;
}

if (code == KeyEvent.VK_DOWN) {
velPlayerY = -2;
}

if (code == KeyEvent.VK_LEFT) {
velPlayerX = -2;
}

if (code == KeyEvent.VK_RIGHT) {
velPlayerX = 2;
}
repaint();
}

public void keyReleased(KeyEvent e) {
code2 = e.getKeyCode();
if (code2 == KeyEvent.VK_UP) {
velPlayerY = 0;
}

if (code2 == KeyEvent.VK_DOWN) {
velPlayerY = 0;
}

if (code2 == KeyEvent.VK_LEFT) {
velPlayerX = 0;
}

if (code2 == KeyEvent.VK_RIGHT) {
velPlayerX = 0;
}
repaint();
}

public void keyTyped(KeyEvent e) {
System.out.println("hi");
}
}
}

最佳答案

使面板可聚焦并请求焦点

public void run() {
JFrame frame = new JFrame("Game");
frame.setSize(800, 600);
frame.setLocation(50, 50);
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.setResizable(true);
GamePanel accessF = new GamePanel();
frame.setContentPane(accessF);
accessF.setFocusable(true);
accessF.requestFocusInWindow();

frame.setVisible(true);
}

关于java - 如何同时运行ActionListener和KeyListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49539429/

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