长话短说,我正在尝试创建一个 java 多人游戏。我正在尝试创建一个 JPanel 战斗动画场景。当服务器向客户端发送攻击消息时,我会弹出战斗屏幕……但没有加载任何内容,并且我收到了一个我不知道如何解决的空指针异常。
主类 -> 有一个 handleAttackMessageFromServer(String msg) 方法
这个方法加载一个新的 Jframe,它有一个扩展 JPanel 的对象
FightFrame(msg){ FightSceneJPanel(msg)}
我试图加载敌方单位 gif 的 JPanel 代码:
public class FightScene extends JPanel{
private ArrayList<Enemy> offense;
private ArrayList<Defense> defense;
private EnemyFactory enemyFactory;
private DefenseFactory defenseFactory;
private boolean ingame;
int NumberOfEnemyTypeA, ..., NumberOfEnemyTypeN;
public FightScene(){
offense = new ArrayList<Enemy>();
defense = new ArrayList<Defense>();
setFocusable(true);
setBackground(Color.RED);
setDoubleBuffered(true);
setSize(652, 480);
setVisible(true);
enemyFactory = new EnemyFactory();
defenseFactory= new DefenseFactory();
}
public void FightScene(String attackmsg){
ingame=true;
// string parsing to figure out how many of what units were sent over
NumberOfEnemyTypeA = Integer.parseint(msg.(....)));
// ...
NumberOFEnemyTypeN = Integer.parseint(msg.(...)));
if(NumberOfEnemyTypeA!=0){
for (int i =1;i<NumberOfEnemyTypeA+1;i++){
theEnemy=enemyFactory.makeEnemy(1, 0-i*40);
offense.add(theEnemy);
}}
System.out.println("Offense size: "+offense.size()); // <<< When i do this, it says offense //size is 0!!.. even when NumberOFEnemyTypeA is 5, 10 or any number>0
}
// and when i try to draw... I get nothing, because ofcourse offense == 0
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
for (int i = 0; i < offense.size(); i++) {
if(offense.get(i) instanceof EnemyTypeA){
EnemyTypeA a = (EnemyTypeA)offense.get(i);
if(a.isVisible()){
g2d.drawImage(a.getImage(), a.getX(), a.getY(), this);
}
}
// ....
if(offense.get(i) instanceof EnemyTypeN){
EnemyTypeN a = (EnemyTypeN)offense.get(i);
if(a.isVisible()){
g2d.drawImage(a.getImage(), a.getX(), a.getY(), this);
}
}
}
}
搞不懂怎么回事!!!
下面是 Frame 加载 ScenePanel 的方式,但 FightFrame 本身是在 main 方法中的 HandleServerAttackMessage() 中调用的。
public void FightFrame(String offensemsg){
JFrame frame = new JFrame("BattleView: ");
frame.setLayout(new BorderLayout());
FightScene sc = new FightScene();
sc.Scene(offensemsg);
frame.add(sc);
frame.setVisible(true);
frame.setSize(652, 480);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}