問題是沒有錯誤,一切正常,即使我在if(keyevent == w)system.out.println(「something」)中寫入內容時也是如此。它也可以工作,但由於某種原因球位置不變,請提出任何建議?Java-can't a ball move
Entity.Java
package FirstGame;
import java.awt.Graphics;
public abstract class Entity {
protected int x,y,w,h;
protected boolean removed=false;
public Entity(int x,int y){
this.x=x;
this.y=y;
}
public void draw(Graphics g){
}
public int getX(){return x;}
public int getY(){return y;}
public int getW(){return w;}
public int getH(){return h;}
}
Player.Java
package FirstGame;
import java.awt.Color;
import java.awt.Graphics;
public class Player extends Entity {
public int xd,yd;
public Player(int x, int y) {
super(x, y);
w=16;
h=16;
}
@Override
public void draw(Graphics g){
g.setColor(Color.orange);
g.fillOval(x, y, w, h);
}
private void move(){
this.x+=xd;
this.y+=yd;
}
public void setXD(int value){
xd=value;
}
public void setYD(int value){
yd=value;
}
}
Dodge.java
package FirstGame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Dodge extends JPanel implements KeyListener{
private int x=5,y=5;
private static String title="Dodge Game";
private static int WIDTH=500;
private static int HEIGHT=400;
private Player player;
// Constructor //
public Dodge(){
setSize(new Dimension(WIDTH,HEIGHT));
setPreferredSize(new Dimension(WIDTH,HEIGHT));
setFocusable(true);
setBackground(Color.BLACK);
addKeyListener(this);
player=new Player(200,200);
}
@Override
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0,getWidth(), getHeight());
player.draw(g);
g.dispose();
repaint();
}
public static void main(String[] args){
Dodge game=new Dodge();
JFrame frame=new JFrame();
frame.setTitle(title);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
@Override
public void keyPressed(KeyEvent e) {
int c=e.getKeyCode();
if(c==KeyEvent.VK_W){
player.setYD(-1);
}
if(c==KeyEvent.VK_S){
player.setXD(-1);
}
if(c==KeyEvent.VK_A){
player.setYD(1);
}
if(c==KeyEvent.VK_D){
player.setXD(1);
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
請勿使用大寫字母表示軟件包名稱。 – davidxxx
好兄弟我是新的java編程soo idk; d – DummyTarget
(a)在Swing中,不要重寫'paint',只能'paintComponent'。 (b)不要在'paint'或'paintComponent'裏重繪'',也不要在'Graphics'上調用'dispose'作爲參數。 (c)我在這裏看不到球。 (d)有一個'移動'但沒有人叫它。 – RealSkeptic