Rok Dolinar Rok Dolinar - 3 months ago 15
Java Question

Adding image to canvas window

I'm trying to add a .png picture to my canvas window, however I'm having some problems. Let's say that im adding different types of objects to my window. There is class Pacman, which extends class GameObject. However, my pacman is currently a rectangle, and I want to replace this rectangle with a picture of a Pacman. I tried 10 different codes but you need to extend either canvas or JFrame. Unfortunately, I can't do this since I already extended class Pacman with class GameObject.

I'm new to object programming, but is there a way to add a picture to a window?


Consider re-designing your GUI program in an M-V-C (model-view-control) fashion, where key is that the model (the logical representation of your program) is distinct from and is ignorant of the view (the visual representation of the program). This way, your Pacman model class can extend your GameObject model class, while the visual representation of Pacman can be a JLabel that holds your pacman image in an ImageIcon.

Edit: either that, or as MadProgrammer states, have the visual representation be drawn on the game's main JPanel as a sprite in its paintComponent(Graphics g) method.

The key bit here being that your logical representation of the game -- mainly the location, movement and interaction of the actors involved such as the Pac Man, the enemies, the "food", the power bits, the maze borders, is coded without regard to GUI, images, or user interactions. This part of the code would use no GUI libraries such as Swing or AWT, would use no KeyListeners or key bindings. It would have a game loop that and logic that would move the non-user controlled elements, it would check for Pac Man and enemy touches, it would have code for Pac-Man states -- normal and empowered -- and logic for what to do when Pac-Man touches an enemy depending on Pac-Man's state. It would have methods that allow another class to move the Pac-Man such as moveRight(), moveLeft(), moveUp(), and moveDown().

The GUI would display the maze and the actors depending on their positions in the model. The GUI would be notified by listeners about changes in the model's state, and would then repaint itself and the new position of the actors. It would have listeners that listen for user interaction and then would pass that information to the controller which would then change the state of the model. For instance, key bindings could notify the control class that the user is pressing the up-arrow, and then the control would call the model's moveUp() method to move Pac-Man up, if no obstacles prevented this from occurring.

For more on the M-V-C and Swing, please check out: