gpt4 book ai didi

java - 在Java中添加KeyListener

转载 作者:行者123 更新时间:2023-12-01 19:49:59 25 4
gpt4 key购买 nike

这是一个小游戏。这里我做了两个相同大小的矩形。每当有人按下键盘上的键时我想移动它们。但我不知道如何添加KeyListener。我在这里查看了以前的答案,但我无法发现我的错误。我什至搜索了谷歌但没有任何线索。这是我的代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class PongGame extends JComponent implements ActionListener {
int ballX = 200;
int ballY = 340;
short ballX_Direction = 1;
short ballY_Direction = 1;
static int Direction1 = 300;
static int Direction2 = 300;
private static keyListener move;
public static void main(String[] args) {
JFrame frame = new JFrame("Pong Game");
PongGame game = new PongGame();
frame.add(game);
frame.pack();
frame.setSize(900,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
Timer t = new Timer(2,game);
t.start();
}
public void paintComponent(Graphics g) {
g.setColor(new Color(0,242,237));
g.fillRect(0,0,900,700);
g.setColor(Color.black);int a = 60;
for(int i = 1;i<=5;i++) {
g.fillRect(444,0+a,12,65);
a = a+125;
}
g.setColor(Color.blue);
g.fillRect(100,Direction2,15,100);
g.fillRect(770,Direction1,15,100);
g.setColor(Color.red);
g.fillOval(ballX,ballY,20,20);
repaint();
}
public void actionPerformed(ActionEvent e) {
ballX = ballX + ballX_Direction;
ballY = ballY + ballY_Direction;
if(ballY >= 660) ballY_Direction = -1;
if(ballY <= 0) ballY_Direction = 1;

if(ballX >= 444-20 && ballY >= 60-20 && ballX <= 444-20 && ballY <= 185-20) {
ballX_Direction = -1;
}
if(ballX >= 444-20 && ballY >= 185-20 && ballX <= 444-20 && ballY <= 250-20) {
ballX_Direction = -1;
}
if(ballX >= 444-20 && ballY >= 250-20 && ballX <= 444-20 && ballY <= 375-20) {
ballX_Direction = -1;
}
if(ballX >= 444-20 && ballY >= 375-20 && ballX <= 444-20 && ballY <= 500-20) {
ballX_Direction = -1;
}
if(ballX >= 444-20 && ballY >= 500-20 && ballX <= 444-20 && ballY <= 625-20) {
ballX_Direction = -1;
}
repaint();
}
}

class keyListener implements KeyListener {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP)
{
PongGame.Direction1 = PongGame.Direction1 - 25
}
if(key == KeyEvent.VK_DOWN)
{
PongGame.Direction1 = PongGame.Direction1 - 25;
}
if(key == '1')
{
PongGame.Direction2 -= 25;
}
if(key == '4')
{
PongGame.Direction2 += 25;
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}

最佳答案

JFrame 有一个方法:

frame.addKeyListener(new keyListener());

它需要添加到 GUI 部分,特别是具有焦点的部分,因为这是操作系统告诉有关输入的信息。

关于java - 在Java中添加KeyListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51745823/

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