我正在製作一款汽車遊戲,我剛剛遇到了屏幕大小問題,它不允許汽車移動(它應該能夠在所有屏幕上移動) ,也許jpanel的大小不是正確的大小。JFrame和JPanel大小在java中沒有變化
主要和JPanel的:
public class MyCarGame extends JPanel implements Runnable {
CarPlayer Player;
public MyCarGame(GUI frame) {
Player = new CarPlayer(0, 0);
this.setSize(WidthFrame,HeightFrame);
this.addKeyListener(new KeyListener());
}
public void draw(Graphics g) {
Player.draw(g);
repaint();
}
/**
* @param args the command line arguments
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
draw(g);
}
@Override
public void run() {
while (true) {
Player.move();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(MyCarGame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private class KeyListener extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
Player.xVel = 3;
break;
case KeyEvent.VK_LEFT:
Player.xVel = -3;
break;
case KeyEvent.VK_UP:
Player.yVel = -3;
break;
case KeyEvent.VK_DOWN:
Player.yVel = 3;
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_LEFT:
Player.xVel = 0;
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_DOWN:
Player.yVel = -1;
break;
}
}
}
public static int WidthFrame = 0;
public static int HeightFrame = 0;
public static void main(String[] args) {
// TODO code application logic here
new GUI().setVisible(true);
}
}
Player類:
public class CarPlayer {
int x;
int y;
Image img;
public int xVel;
public int yVel;
public CarPlayer(int x,int y){
img= new ImageIcon("images/PlayerCar.png").getImage();
this.x=x;
this.y=y;
xVel=0;
yVel=-1;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move(){
if(x+xVel<(MyCarGame.WidthFrame-50) && x+xVel>0)
x+=xVel;
if(y+yVel<(MyCarGame.HeightFrame-100) && y+yVel>0)
y+=yVel;
if(x<0){
xVel=0;
}
if(y<0){
yVel=0;
}
if(y>(MyCarGame.HeightFrame-100)){
yVel=0;
}
if(x>(MyCarGame.WidthFrame-50)){
xVel=0;
}
}
public void draw(Graphics g){
g.drawImage(img, x, y,50,100, null);
}
}
Frame類:
public class GUI extends javax.swing.JFrame {
/**
* Creates new form GUI
*/
MyCarGame g;
public GUI() {
this.setFocusable(false);
this.setResizable(false);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
MyCarGame.WidthFrame=this.getWidth();
MyCarGame.HeightFrame=this.getHeight();
g=new MyCarGame(this);
this.add(g);
g.setLocation(0, 0);
g.requestFocusInWindow();
Thread t= new Thread(g);
t.start();
}
}
1)爲了更好地幫助越早,後期一個[MCVE](http://stackoverflow.com/help/mcve)(最小完整和可驗證示例)。 2)對代碼塊使用一致的邏輯縮進。代碼的縮進旨在幫助人們理解程序流程。 –
使用Swing'Timer'進行動畫。 –
'WidthFrame'和'HeightFrame'是'0'?你能指望什麼。不要爲此使用'static'字段,傳遞'Player'需要知道的信息,即組件的實際大小... – MadProgrammer