【发布时间】:2014-05-05 17:17:00
【问题描述】:
所以基本上我正在尝试制作一个类似于 2D 迷宫的游戏,您可以在其中自己创建地图或加载预制的地图。单击相应的 JButton 后,您可以通过提供新的所需对象的坐标来更改地图的图块,这些对象可以是墙、草、敌人、炸弹、武器、英雄等。我的问题是:到目前为止,我一直只使用 JLabels 在地图中放置草的图像,因为它们是英雄可以移动的“基本图块”,然后我试图将它们更改为自定义不同类的对象,所以当英雄移动到其中一个时,它会触发不同的动作,但看起来 JLabel 只能包含文本或图像,那么我应该怎么做呢?这是代码(对不起,它是西班牙语):
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);
}
}
【问题讨论】:
-
谁强迫你使用
JLabel? -
取决于你想做什么。你只是告诉我们
JLabel所做的事情是不够的,但你没有告诉我们你真正需要什么。 -
我需要放置另一个类的实例,例如墙或敌人