这是一个小游戏。在这里,我制作了 2 个相同大小的矩形。每当有人按下键盘上的键时,我都想移动它们。但我不知道如何添加 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();
}
largeQ
相关分类