Question

So basically I'm trying to make a 2D maze-like game where you can either create a map yourself or load a premade one. You change the tiles of the map by giving the coordinates of the new desired object which can be a wall, grass, enemy, bomb, weapon, the hero, etc, after clicking the corresponding JButton. My question is: up until now I've been using just JLabels to place images of the grass in the map because they're the "basic tiles" on which the hero can move, and then I'm trying to change those to custom objects of the different classes so when the hero moves to one of them it triggers different actions, but it looks like a JLabel can only contain text or images, so how should I do it then? This is the code (I'm sorry it's in spanish):

public class Tablero extends JFrame {

private int numFilas;
private int numColumnas;
private int numMuros;

public Tablero(final int numFilas, final int numColumnas, final int numMuros) {
    this.numFilas = numFilas;
    this.numColumnas = numColumnas;
    this.numMuros = numMuros;
    JFrame tablero = new JFrame();
    JPanel contenedor = new JPanel();
    final JLabel[][] casilla = new JLabel[60][60];
    tablero.setSize(1280, 720);
    contenedor.setSize(1280, 720);
    tablero.add(contenedor);

    for (int x = 0; x < this.numFilas; x++) {
        for (int y = 0; y < this.numColumnas; y++) {
            casilla[x][y] = new JLabel();
            casilla[x][y].setIcon(new ImageIcon("C:\\Users\\Andres\\Desktop\\Programación orientada a objetos\\Juego\\build\\classes\\juego\\pasto.png"));
            contenedor.add(casilla[x][y]);
        }
    }
    JOptionPane.showMessageDialog(null, "Cree a continuación el héroe");
    int coorX = Integer.parseInt(JOptionPane.showInputDialog("Digite la coordenada en x del héroe: "));
    int coorY = Integer.parseInt(JOptionPane.showInputDialog("Digite la coordenada en y del héroe: "));
    int lives = Integer.parseInt(JOptionPane.showInputDialog("Digite la cantidad de vidas del héroe: "));
    final Heroe heroe = new Heroe(coorX, coorY, lives);

    JButton añadirMuros = new JButton("Añadir muros");
    contenedor.add(añadirMuros);
    añadirMuros.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            Muro[] muros = new Muro[numMuros];
            for (int i = 0; i < numMuros; i++) {
                int coorX = Integer.parseInt(JOptionPane.showInputDialog("Digite la coordenada en x del muro # " + i + 1));
                int coorY = Integer.parseInt(JOptionPane.showInputDialog("Digite la coordenada en y del muro # " + i + 1));
                muros[i] = new Muro(coorX, coorY, heroe);
                casilla[coorX][coorY] = new JLabel();
            }
            System.out.println("Clicked! muros");
        }
    });

    JButton añadirBombas = new JButton("Añadir bombas");
    contenedor.add(añadirBombas);

    JButton añadirPistolas = new JButton("Añadir pistolas");
    contenedor.add(añadirPistolas);

    JButton añadirBallestas = new JButton("Añadir ballestas");
    contenedor.add(añadirBallestas);

    JButton añadirEnemigos = new JButton("Añadir enemigos");
    contenedor.add(añadirPistolas);

    JButton determinarEntrada = new JButton("Determinar entrada");
    contenedor.add(determinarEntrada);

    JButton determinarSalida = new JButton("Determinar salida");
    contenedor.add(determinarSalida);

    tablero.setVisible(true);
    tablero.setResizable(true);
    tablero.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

}

Was it helpful?

Solution

Yes, a JLabel can only contain text or an ImageIcon.

You can use a JPanel to draw images directly. Your Wall and Enemy classes can draw a representation of themselves on a JPanel.

Here's a GameImages and GuessingGamePanel from a game I put together. The GuesssingGamePanel draws the images from the GameImages class.

package com.ggl.guessing.game.view;

import java.awt.Dimension;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class GameImages {

    private Image backgroundImage;
    private Image victoryImage;

    public GameImages() {
        readBackgroundImage();
        readVictoryImage();
    }

    private void readBackgroundImage() {
        Image image = null;
        try {
            URL url = getClass().getResource("/v8k3reduced.jpg");
            image = ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.backgroundImage = image;
    }

    private void readVictoryImage() {
        Image image = null;
        try {
            URL url = getClass().getResource("/r7f8reduced.jpg");
            image = ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.victoryImage = image;
    }

    public Image getBackgroundImage() {
        return backgroundImage;
    }

    public Dimension getPreferredSize() {
        return new Dimension(backgroundImage.getWidth(null),
                backgroundImage.getHeight(null));
    }

    public Image getVictoryImage() {
        return victoryImage;
    }

}

.

package com.ggl.guessing.game.view;

import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JPanel;

import com.ggl.guessing.game.model.GuessingGameModel;

public class GuessingGamePanel extends JPanel {

    private static final long   serialVersionUID    = 
            -2429103448910749064L;

    private boolean guessed;

    private Dimension guessesPanelDimension;

    private GameImages gameImages;

    private GuessesPanel guessesPanel;

    private GuessingGameFrame frame;

    private GuessingGameModel model;

    public GuessingGamePanel(GuessingGameFrame frame,
            GuessingGameModel model, GameImages gameImages, 
            Dimension guessesPanelDimension) {
        this.frame = frame;
        this.model = model;
        this.gameImages = gameImages;
        this.guessesPanelDimension = guessesPanelDimension;
        this.guessed = false;

        createPartControl();
    }

    private void createPartControl() {
        this.setLayout(null);
        this.setPreferredSize(gameImages.getPreferredSize());

        guessesPanel = new GuessesPanel(frame, model);
        Dimension gp = guessesPanelDimension;
        Dimension tp = gameImages.getPreferredSize();
        int x = (tp.width - gp.width) / 2;
        int y = (tp.height - gp.height) / 2;
        guessesPanel.getPanel().setBounds(x, y, gp.width, gp.height);
        this.add(guessesPanel.getPanel());
    }

    public void setGuessed(boolean guessed) {
        this.guessed = guessed;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawImage(gameImages.getBackgroundImage(), 0, 0, null);
        if (guessed) {
            g.drawImage(gameImages.getVictoryImage(), 0, 0, null);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top