所以这是我的全部keying.java:
package com.Bench3.mygame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
public class Keying extends JPanel {
public Rectangle character;
public int charW = 24;
public int charH = 36;
public boolean right = false;
public boolean left = false;
public Keying(Display f, Images i){
character = new Rectangle(180, 180, charW, charH);
f.addKeyListener(new KeyAdapter(){ // <-- line 20
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
right = true;
character.x += 1;
}
if(e.getKeyCode() == KeyEvent.VK_A){
left = true;
character.x -= 1;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_A){
left = false;
}
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.WHITE);
g.fillRect(character.x, character.y, character.width, character.height);
if(right){
character.x += 1;
}
if(left){
character.x -= 1;
}
repaint();
}
}
代码 f.addKeyListener(new KeyAdapter(){(第20行)
我正在尝试制作一款游戏,键盘java是我唯一的问题,我正在按照视频的指南进行操作,而我正在做的就是他所做的但是我遇到了错误。
错误:
Description: KeyAdapter cannot be resolved to a type
Resource: Keying.java
Path: /My First Game In Java/src/com/Bench3/mygame
Location: line 20
Type: Java Problem
The method addKeyListener(KeyListener) in the type Component is not applicable for the arguments (new KeyAdapter(){})
答案 0 :(得分:0)
问题可能是字符Rectangle必须是最终的:
public final Rectangle character;
如果您有匿名课程(f.addKeyListener(new KeyAdapter(){...})
- &gt; KeyAdaptor
是匿名课程),他们需要“最终”实例才能工作,否则他们不知道character
在实例化类和调用类时,Rectangle已经发生了变化。
答案 1 :(得分:0)
您正在尝试使用KeyAdapter
,但您没有导入它。 KeyAdapter
is in java.awt.event
。您要导入java.awt.*
和java.awt.event.KeyEvent
。这些都不会带来java.awt.event.KeyAdapter
。
您还需要导入java.awt.event.KeyAdapter
。
通常,“KeyAdapter无法解析为类型”之类的错误意味着编译器无法在任何地方找到名为“KeyAdapter”的类。这通常指向缺少导入或输入错误。
只需指出这一点:导入java.awt.*
不会导入java.awt
的子包,例如它不会自动引入java.awt.event.*
。