大家好我使用netbeans 7.2.1 并且正在学习键盘输入教程
这段代码应该在JFrame中绘制一个圆圈,它就是这样做的 但是然后应该使用箭头键输入来移动它,它不会
谢谢你的帮助:)
package gamefirstclass;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class GameFirstClass extends JFrame {
//Variables
int y, x;
//Double Buffer
private Image dbImage;
private Graphics dbg;
//Window Basics
public GameFirstClass() {
addKeyListener(new AL());
setTitle("Add window title");
setSize(800, 700);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 150;
y = 150;
}
// main
public static void main(String[] args) {
new GameFirstClass();
}
//Controls
public class AL extends KeyAdapter {
@Override
public void keyPressed(KeyEvent event) {
int keyCode = event.getKeyCode();
if (keyCode == event.VK_LEFT)
{
x--;
}
if (keyCode == event.VK_RIGHT)
{
x++;
}
if (keyCode == event.VK_UP)
{
y--;
}
if (keyCode == event.VK_DOWN)
{
y++;
}
}
@Override
public void keyReleased(KeyEvent event) {
}
}
//Double Buffer
@Override
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.fillOval(x, y, 15, 15);
repaint();
}
}
答案 0 :(得分:1)
好的,有一个问题:你的if statements!
基本上,在keyListener
if statements
中,semicolon
因执行x
而无法执行。
这些块都是剩下的,对semicolons
的修改是相同的。只需删除repaint()
,我相信它会起作用
此外,请勿从paintComponent()
致电repaints
,因为您每次都会产生大量setFocusable(true)
。我不知道这是否重要,但您应在JFrame
上致电KeyListener
以确保{{1}}有效。
祝你好运!