没有错误或某事,只是透明屏幕(它会复制背景)和绘制的椭圆形,但每当我尝试在键盘上键入箭头键时它都不会工作。我添加了KeyListener并将类扩展到JFrame,但它仍然没有做任何事情。我知道这只是初学者的事,但我自己也是初学者,这一直困扰着我:/。另外,我也使用了repaint(); ,但它仍然重新渲染背景?感谢您的帮助!
package JavaMain;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class javamain extends JFrame {
int x, y;
private static final long serialVersionUID = 1L;
public class AL extends KeyAdapter {
private int keycode;
@SuppressWarnings("static-access")
public void keypress(KeyEvent event) {
keycode = event.getKeyCode();
if (keycode == event.VK_LEFT) {
x -= 10;
}
if (keycode == event.VK_RIGHT) {
x += 10;
}
if (keycode == event.VK_UP) {
y -= 10;
}
if (keycode == event.VK_DOWN) {
y += 10;
}
}
public void keyrelease(KeyEvent e) {
}
}
public javamain() {
addKeyListener(new AL());
setTitle("Statistic");
setSize(600, 800);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 200;
y = 200;
}
public void paint(Graphics g) {
g.fillOval(x, y, 20, 20);
repaint();
}
public static void main(String[] args) {
new javamain();
}
}
答案 0 :(得分:0)
错误在于您的KeyListener。
AL类没有使用正确的方法名称。
据我所知,应该是keyPressed和keyReleased。
private class AL extends KeyAdapter {
public void keyPressed(KeyEvent event) {
int keycode = event.getKeyCode();
if (keycode == KeyEvent.VK_LEFT) {
x -= 10;
}
if (keycode == KeyEvent.VK_RIGHT) {
x += 10;
}
if (keycode == KeyEvent.VK_UP) {
y -= 10;
}
if (keycode == KeyEvent.VK_DOWN) {
y += 10;
}
}
public void keyReleased(KeyEvent e) {
}
}
在不更改任何其他代码的情况下,这似乎有用。