我的程序有3个java文件,即Frame,Dude(包含字符)和Board(实现actionListener)。我的程序没有抛出任何错误,图像(背景和字符)呈现良好。但这个角色没有前进。
import javax.swing.*;
public class Frame {
public static void main(String[] args){
JFrame frame= new JFrame("2D Game");
frame.add(new Board());
frame.setVisible(true);
frame.setSize(1200, 600);
}
}
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Dude {
int x, dx, y;
Image still;
public Dude(){
ImageIcon i = new ImageIcon("/home/amitabh/Pictures/man1.jpg");
still= i.getImage();
x=10;
y=172;
}
public void move(){
x=x+dx;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public Image getImage(){
return still;
}
public void keyPressed(KeyEvent e){
int key= e.getKeyCode();
if(key== KeyEvent.VK_LEFT);
dx= -1;
if(key== KeyEvent.VK_RIGHT);
dx= 1;
}
public void keyReleased(KeyEvent e){
int key= e.getKeyCode();
if(key==KeyEvent.VK_LEFT);
dx=0;
if(key==KeyEvent.VK_RIGHT);
dx=0;
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener{
Image img;
Timer time;
Dude p;
public Board(){
p= new Dude();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i= new ImageIcon("/home/amitabh/Pictures/game1.png");
img= i.getImage();
time= new Timer(5,this);
time.start();
}
@Override
public void actionPerformed(ActionEvent e) {
p.move();
repaint();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d= (Graphics2D)g;
g2d.drawImage(img, 0,0, null);
g2d.drawImage(p.getImage(), p.getX(), p.getY(), null);
}
public class AL extends KeyAdapter{
public void keyReleased(KeyEvent e){
p.keyReleased(e);
}
public void KeyPressed(KeyEvent e){
p.keyPressed(e);
}
}
}
答案 0 :(得分:2)
首先仔细谈谈:
if (key == KeyEvent.VK_LEFT);
这看起来对你有意思吗?
if (key == KeyEvent.VK_LEFT); // <--- What's the ; doing here?
将其更改为......
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
而且,是的,这就是为什么鼓励您使用{ ... }
接下来,仔细看看......
public void KeyPressed(KeyEvent e) {
看到有什么不对吗?为什么它以大写K
开头,这不是正确的方法签名
更改为更像......
@Override
public void keyReleased(KeyEvent e) {
p.keyReleased(e);
}
@Override
public void keyPressed(KeyEvent e) {
p.keyPressed(e);
}
是的,这就是为什么鼓励您使用@Override
;)
最后将您的paint
方法更改为paintComponent
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
我们鼓励您在执行自定义绘画时覆盖paintComponent
,这往往会导致更少的问题
我还会邀请您查看Key Bindings API并优先于KeyListener
,因为它可以更好地控制触发关键事件所需的焦点水平
我还建议您覆盖getPreferredSize
的{{1}}并从那里返回您的首选尺寸,而不是设置框架的尺寸。帧大小包括帧的装饰,因此您的内容小于帧大小