问题描述
由于某种原因,屏幕的左上角有一个奇怪的白色矩形。我也试图在JPanel上画一个正方形,但似乎没有用。我可能还应该提到,我刚刚开始学习Jframes和Jpanels(尽管我做了一些简单的应用程序),所以下面看到的代码可能不是很干净:
主要
import javax.swing.*;
public class Main {
public static void main(String[] agrs) {
JFrame frame = new JFrame("Space Ship");
new GameFrame(frame);
new GameGraphics();
}
}
GameFrame
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameFrame {
GameGraphics game;
GameFrame(JFrame frame) {
game = new GameGraphics();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.setResizable(false);
frame.setVisible(true);
frame.pack();
}
}
GameGraphics
import javax.swing.*;
import java.awt.*;
public class GameGraphics extends JPanel implements Runnable {
static final int SCREEN_WIDTH = 1000;
static final int SCREEN_HEIGHT = SCREEN_WIDTH * 9 / 16;
static final Dimension SCREEN = new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT);
Player player;
int playerHeight = 25;
int playerWidth = 25;
int playerX = (SCREEN_WIDTH/2) - 200;
int playerY = SCREEN_HEIGHT/2;
GameGraphics() {
this.setPreferredSize(SCREEN);
this.setBackground(Color.BLACK);
}
public void start() {}
public void newPlayer() {
player = new Player(playerX,playerY,playerWidth,playerHeight);
}
public void newFireball() {}
public void collisons() {}
public void gameOver() {}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
player.draw(g);
}
@Override
public void run() {}
}
播放器
import javax.swing.*;
import java.awt.*;
public class Player extends Rectangle {
int x = 200;
int y = 200;
Player(int playerX,int playerY,int playerWidth,int playerHeight) {
super.setBounds(x,y,width,height);
}
public void draw(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(x,height);
}
}
提前谢谢!
解决方法
您的主要方法中new GameGraphics()
语句的意义是什么?
它不是必需的,也不应该在那里。摆脱它。
Player(int playerX,int playerY,int playerWidth,int playerHeight) {
super.setBounds(x,y,width,height);
}
以上代码的意义是什么?您在构造函数中传入参数,但随后再也不会使用这些参数。
您的代码只能编译,因为Rectangle类具有这4个字段,但是它们将具有默认值(而不是您期望的值),这可能会导致绘制问题。
不要扩展矩形!您不会在Rectangle类中添加任何新功能。
您的Player
类不需要扩展任何类。相反,您的Player
类应类似于:
public class Player {
int playerX;
int playerY;
int playerWidth;
int playerHeight;
Player(int playerX,int playerHeight) {
this.playerX = playerX;
this.playerY = playerY;
this.playerWidth = playerWidth;
this.playerHeight = playerHeight;
}
public void draw(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(playerX,playerY,playerWidth,playerHeight);
}
}
如sorifiend所述,您也没有创建Player对象的实例。
,您似乎拥有NullPointerException
,因为player
类中从未定义过GameGraphics
,并且正在导致图形故障:
Player player;
您似乎已经创建了一种设置播放器的方法,但从未被调用:
public void newPlayer() {
player = new Player(playerX,playerHeight);
}
一种解决方案可能是在newPlayer()
构造函数中调用GameGraphics()
方法:
GameGraphics() {
this.setPreferredSize(SCREEN);
this.setBackground(Color.BLACK);
//add it here
newPlayer();
}
或者您可以这样创建播放器:
public class GameGraphics extends JPanel implements Runnable {
//...
Player player = new Player(playerX,playerHeight);
//...
一旦修复,就不会再引起问题。