我正在为一个类项目制作pong,我不知道如何使用键盘输入。我在网上看过很多指南,但我所做的一切都不管用。知道为什么它没有注册任何键盘输入吗?我很肯定我有所有正确的进口。
package pong2;
import java.awt.color.*;
import javax.swing.JFrame;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.logging.Level;
import java.util.logging.Logger;
public class graphic extends Canvas implements KeyListener
{
int y1 = 450;
int y2 = 450;
public static void main(String[] args) throws InterruptedException
{
jframe公司
JFrame frame = new JFrame("Pong");
Canvas canvas = new graphic();
canvas.setSize(1920,1080);
frame.add(canvas);
frame.setBackground(Color.BLACK);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(new KeyListener() );
frame.repaint();
}
密钥侦听器
@Override
public void keyTyped(KeyEvent e)
{
//System.out.println("Key Typed");
}
@Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_DOWN);
{
//System.out.println("Key Pressed " + e.getKeyCode());
y2 = y2 - 10;
repaint();
}
if(e.getKeyCode() == KeyEvent.VK_UP);
{
y2 = y2 + 10;
repaint();
}
}
@Override
public void keyReleased(KeyEvent e)
{
//System.out.println("Key Released");
}
乒乓板图形
public void paint(Graphics g)
{
super.paint(g);
//Background
g.setColor(Color.BLACK);
g.fillRect(0,0,1920,1080);
//Goals
g.setColor(Color.WHITE);
g.fillRect(0,0,50,1080);
g.fillRect(1870,0,50,1080);
//Paddles
g.fillRect(120,y1,20,150);
g.fillRect(1790,y2,20,150);
//Ball
g.fillRect(950,525,20,20);
}
}
1条答案
按热度按时间x759pob21#
自从你的
graphic
类扩展Canvas
和工具KeyListener
你有你的Canvas
引用指向graphic
对象i-eCanvas canvas = new graphic();
所以你必须注册canvas
听键盘输入。改变
frame.addKeyListener(new KeyListener())
到frame.addKeyListener((KeyListener) canvas);
或frame.addKeyListener((graphic) canvas);