Erreur de compilation

Fermé
myriam - Modifié par KX le 27/05/2014 à 07:45
 myriam - 27 mai 2014 à 20:00
Bonjour,
je dois faire un projet sur le jeux Stratege, je n'ai pas des erreurs de syntaxe mais au moment de la compilation il m'affiche des erreurs! j'ai essayer de mettre ces erreurs en commentaire mais sans solution!
Je vous remercie d'avance de vos solutions
Exception in thread "main" java.lang.NullPointerException
at Strategoo.PlateauCase.createGuiPiece(PlateauCase.java:155)
at Strategoo.PlateauCase.<init>(PlateauCase.java:59)
at Strategoo.PlateauCase.main(PlateauCase.java:338)

package Strategoo;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class PlateauCase extends JPanel {
 
 private static final long serialVersionUID = 1L;
 private static final int BOARD_START_X = 384;
 private static final int BOARD_START_Y = 64;

 private static final int SQUARE_WIDTH = 64;
 private static final int SQUARE_HEIGHT = 64;

 private static final int PIECE_WIDTH = 64;
 private static final int PIECE_HEIGHT = 64;
 
 private static final int PIECES_START_X = BOARD_START_X + (int)(SQUARE_WIDTH/2.0 - PIECE_WIDTH/2.0);
 private static final int PIECES_START_Y = BOARD_START_Y + (int)(SQUARE_HEIGHT/2.0 - PIECE_HEIGHT/2.0);
 
 private static final int DRAG_TARGET_SQUARE_START_X = BOARD_START_X - (int)(PIECE_WIDTH/2.0);
 private static final int DRAG_TARGET_SQUARE_START_Y = BOARD_START_Y - (int)(PIECE_HEIGHT/2.0);
 
 
 private Image imgBackground;
 private JLabel lblGameState;
 private Stratego strategoGame;
 private Piece pieceee;
 
 private List<ActionEchiquier> guiPieces = new ArrayList<ActionEchiquier>();
 
 private ActionEchiquier dragPiece; // currently dragged game piece

 private AffichageCase lastMove; // the last executed move (used for highlighting)
 
 public PlateauCase() {
  this.setLayout(null);
  
  Image urlBackgroundImg = Toolkit.getDefaultToolkit().createImage("images/board.png");
  this.imgBackground = new ImageIcon(urlBackgroundImg).getImage();
  
  // create chess game
  this.strategoGame = new Stratego();
  
  //wrap game pieces into their graphical representation
  for (Piece piece : this.strategoGame.getPieces()) {
   createGuiPiece(piece); //ligne 59 erreur!
  }
 
  GestionnaireAffichage listener = new GestionnaireAffichage(this.guiPieces,this);
  this.addMouseListener(listener);
  this.addMouseMotionListener(listener);

  
  // button to reset and start new game
  JButton btnNewGame = new JButton("nouvelle partie");
  btnNewGame.addActionListener(new NewGameButtonActionListener(this));
  btnNewGame.setBounds(900, 64, 120, 30);
  this.add(btnNewGame);

  // label to display game state
  String labelText = this.getGameStateAsText();
  this.lblGameState = new JLabel(labelText);
  lblGameState.setBounds(255, 65, 120, 20);
  lblGameState.getBackground(); 
  lblGameState.setOpaque(true);
  lblGameState.setHorizontalAlignment( SwingConstants.CENTER ); 
  lblGameState.setBackground(Color.GRAY);
  lblGameState.setForeground(Color.BLACK);
  this.add(lblGameState);

  // create application frame and set visible
  //
  JFrame f = new JFrame();
  f.setVisible(true);
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  f.add(this);
  f.setResizable(false);
  f.setSize(1024,768);
 }
 

 /**
  * @return textual description of current game state
  */
 private String getGameStateAsText() {
  String state = "unknown";
  switch (this.strategoGame.getGameState()) {
   case Stratego.GAME_STATE_BLUE: state = "bleu";break;
   case Stratego.GAME_STATE_END: state = "partie finie";break;
   case Stratego.GAME_STATE_RED: state = "rouge";break;
   case Stratego.GAME_STATE_LAYOUTRED: state = "placer rouge";break;
   case Stratego.GAME_STATE_LAYOUTBLUE: state = "placer bleu";break;
   case Stratego.GAME_STATE_SWITCH: state = "changer joueur";break;
  }
  return state;
 }
 private Image getImageForPiece(int couleur, int type) {
  String filename = "";

  filename += (couleur == Piece.COULEUR_BLEU ? "b" : "r");
  switch (type) {
   case Piece.TYPE_DRAPEAU:
    filename += "dr";
    break;
   case Piece.TYPE_BOMBE:
    filename += "b";
    break;
   case Piece.TYPE_GENERAL:
    filename += "g";
    break;
   case Piece.TYPE_LIEUTENANT:
    filename += "l";
    break;
   case Piece.TYPE_SERGENT:
    filename += "s";
    break;
   case Piece.TYPE_ECLAIREUR:
    filename += "e";
    break;
   case Piece.TYPE_DEMINEUR:
    filename += "de";
    break;
   case Piece.TYPE_ASSASSIN:
    filename += "a";
    break;
  }
  filename += ".png";

  Image urlPieceImg = Toolkit.getDefaultToolkit().createImage("images/"+filename);
   if (urlPieceImg != null) {
    return new ImageIcon(urlPieceImg).getImage();
    } 
    else {
          System.err.println("Couldn't find file: " + filename);
          return null;
      }
    
   
   
  }
 private void createGuiPiece() {
  Image img = this.getImageForPiece(pieceee.getColor(), pieceee.getType()); // ligne 155 erreur
  ActionEchiquier guiPiece = new ActionEchiquier(img, pieceee);
  this.guiPieces.add(guiPiece);
 }

 protected void paintComponent(Graphics g) {

  // draw background
  g.drawImage(this.imgBackground, 0, 0, null);

  // draw pieces
  for (ActionEchiquier guiPiece : this.guiPieces) {
   if( !guiPiece.isDefeated()){
    g.drawImage(guiPiece.getImage(), guiPiece.getX(), guiPiece.getY(), null);
   }
  }
  
  // draw last move, if user is not dragging game piece
  if( !isUserDraggingPiece() && this.lastMove != null ){
   int highlightSourceX = convertColumnToX(this.lastMove.sourceColumn);
   int highlightSourceY = convertRowToY(this.lastMove.sourceRow);
   int highlightTargetX = convertColumnToX(this.lastMove.targetColumn);
   int highlightTargetY = convertRowToY(this.lastMove.targetRow);
   
   g.setColor(Color.GRAY);
   g.drawRoundRect( highlightSourceX+4, highlightSourceY+4, SQUARE_WIDTH-8, SQUARE_HEIGHT-8,100,100);
   g.drawRoundRect( highlightTargetX+4, highlightTargetY+4, SQUARE_WIDTH-8, SQUARE_HEIGHT-8,100,100);
  }
  
  // draw valid target locations, if user is dragging a game piece
  if( isUserDraggingPiece() ){
   
   RegleJeux moveValidator = this.strategoGame.getMoveValidator();
   
   // iterate the complete board to check if target locations are valid
   for (int column = Piece.COLUMN_A; column <= Piece.COLUMN_H; column++) {
    for (int row = Piece.ROW_1; row <= Piece.ROW_8; row++) {
     int sourceRow = this.dragPiece.getPiece().getRow();
     int sourceColumn = this.dragPiece.getPiece().getColumn();
     
     // check if target location is valid
     if( moveValidator.isMoveValid( new AffichageCase(sourceRow, sourceColumn, row, column)) ){
      
      int highlightX = convertColumnToX(column);
      int highlightY = convertRowToY(row);
      
      // draw a black drop shadow by drawing a black rectangle with an offset of 1 pixel
      g.setColor(Color.BLACK);
      g.drawRoundRect( highlightX+5, highlightY+5, SQUARE_WIDTH-8, SQUARE_HEIGHT-8,10,10);
      // draw the highlight
      g.setColor(Color.GREEN);
      g.drawRoundRect( highlightX+4, highlightY+4, SQUARE_WIDTH-8, SQUARE_HEIGHT-8,10,10);
     }
    }
   }
  }
  
  
  // draw game state label
  this.lblGameState.setText(this.getGameStateAsText());
 }

 /** 
  * @return true if user is currently dragging a game piece
  */
 private boolean isUserDraggingPiece() {
  return this.dragPiece != null;
 }

 /*public static void main(String[] args){
  new PlateauCase();
 }*/
 
 /**
  * switches between the different game states 
  
 public void changeGameState() {
  this.strategoGame.changeGameState();
  this.lblGameState.setText(this.getGameStateAsText());
 }*/

 /**
  * @return current game state
  */
 public int getGameState() {
  return this.strategoGame.getGameState();
 }
 
 /**
  * convert logical column into x coordinate
  * @param column
  * @return x coordinate for column
  */
 public static int convertColumnToX(int column){
  return PIECES_START_X + SQUARE_WIDTH * column;
 }
 
 /**
  * convert logical row into y coordinate
  * @param row
  * @return y coordinate for row
  */
 public static int convertRowToY(int row){
  return PIECES_START_Y + SQUARE_HEIGHT * (Piece.ROW_8 - row);
 }
 
 /**
  * convert x coordinate into logical column
  * @param x
  * @return logical column for x coordinate
  */
 public static int convertXToColumn(int x){
  return (x - DRAG_TARGET_SQUARE_START_X)/SQUARE_WIDTH;
 }
 
 /**
  * convert y coordinate into logical row
  * @param y
  * @return logical row for y coordinate
  */
 public static int convertYToRow(int y){
  return Piece.ROW_8 - (y - DRAG_TARGET_SQUARE_START_Y)/SQUARE_HEIGHT;
 }

 /**
  * change location of given piece, if the location is valid.
  * If the location is not valid, move the piece back to its original
  * position.
  * @param dragPiece
  * @param x
  * @param y
  */
 public void setNewPieceLocation(ActionEchiquier dragPiece, int x, int y) {
  int targetRow = PlateauCase.convertYToRow(y);
  int targetColumn = PlateauCase.convertXToColumn(x);
  
  if( targetRow < Piece.ROW_1 || targetRow > Piece.ROW_8
    || targetColumn < Piece.COLUMN_A || targetColumn > Piece.COLUMN_H){
   // reset piece position if move is not valid
   dragPiece.resetToUnderlyingPiecePosition();
  
  }else{
   //change model and update gui piece afterwards
   System.out.println("moving to "+targetRow+"/"+targetColumn);
   AffichageCase move = new AffichageCase( dragPiece.getPiece().getRow(), dragPiece.getPiece().getColumn()
     , targetRow, targetColumn);
   boolean wasMoveSuccessful = this.strategoGame.movePiece( move );
   
   // if the last move was successfully executed, we remember it for
   // highlighting it in the user interface
   if( wasMoveSuccessful ){
    this.lastMove = move;
   }
   
   
   dragPiece.resetToUnderlyingPiecePosition();
  }
 }
 
 /**
  * @param guiPiece - set the gui piece that the user is current dragging
  */
 public ActionEchiquier setDragPiece(ActionEchiquier guiPiece) {
  return this.dragPiece = guiPiece;
 }
 
 /**
  * @return the gui piece that the user is currently dragging
  */
 public ActionEchiquier getDragPiece(){
  return this.dragPiece;
 }

 public void newGame(){
  //JFrame.dispose();
  //dispose(StrategoGui());
  this.strategoGame = null;
  //this.StrategoGui = null;
  this.setVisible(false);
  new PlateauCase();

 }






 public static void main(String[] args){
  new PlateauCase();//ligne 344
 }
}

2 réponses

KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
27 mai 2014 à 07:44
Bonjour,

Si tu as une NullPointerException sur
getImageForPiece(pieceee.getColor(), pieceee.getType());
c'est parce que
pieceee==null
en effet tu ne lui affecte jamais de valeur,
pieceee = new Piece()
par exemple.
1
Bonjour,

merci pour ton aide, j'ai rectifié l'erreur comme tu m'as dit mais ça m'affiche ça maintenant !

Exception in thread "Image Fetcher 3" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
at java.awt.image.Raster.createPackedRaster(Raster.java:455)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1015)
at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:228)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:537)
at apple.awt.OSXImageRepresentation.setPixels(OSXImageRepresentation.java:58)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:120)
merci beaucoup
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
27 mai 2014 à 18:29
Déjà pour une OutOfMemoryError le numéro de ligne n'est pas pertinent
Ça pourrait planter n'importe où dès lors que la mémoire est insuffisante.

Ensuite soit ta configuration de JVM est insuffisante et il faut augmenter la valeur du Xmx, soit tu as une boucle qui va créer à l'infini le même objet en mémoire. Par exemple tu charges peut être plusieurs fois la même image depuis le fichier au lieu de réutiliser l'objet correspondant.

Remarque : tu peux éventuellement utiliser un programme d'analyse de la JVM pour identifier où tu as ta fuite mémoire.
0
merci
0