我一直在尝试将一个 JLabel 放在另一个 Roguelike 之上。不幸的是,它似乎不起作用。到目前为止,这是我的代码:
public void updateDraw(int direction){
int[] pos = Dungeon.getPos();
for(int i=pos[1]-(DISPLAY_Y_SIZE/2) ; i<pos[1]+(DISPLAY_Y_SIZE/2) ; i++){
for(int j=pos[0]-(DISPLAY_X_SIZE/2) ; j<pos[0]+(DISPLAY_X_SIZE/2) ; j++){
labelGrid[i-(pos[1]-(DISPLAY_Y_SIZE/2))][j-(pos[0]-(DISPLAY_X_SIZE/2))].setIcon(tiles[Dungeon.getMapTile(i,j)].getIcon());
}
}
labelGrid[DISPLAY_Y_SIZE/2][DISPLAY_X_SIZE/2].add(character);
this.repaint();
}
我读过一些其他问题的解决方案,它们都是通过简单地将 JLabel 添加到另一个问题来实现的。它在这里没有按预期工作,知道为什么吗?
PS:我不想为我的 JPanel 使用 JLayeredPane。
最佳答案
一种替代方案
不要使用组件(即 JLabels)创建游戏环境。相反,您可以绘制所有游戏对象。
例如,如果您正在执行以下操作:
JLabel[][] labelGrid = JLabel[][];
...
ImageIcon icon = new ImageIcon(...);
JLabel label = new JLabel(icon);
...
for(... ; ... ; ...) {
container.add(label);
}
您可以一起删除标签,并使用 Images
而不是 ImageIcons
,然后您可以将所有图像绘制到单个组件表面。也许是这样的:
public class GamePanel extends JPanel {
Image[][] images = new Image[size][size];
// init images
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image,/* Crap! How do we know what location? Look Below */);
}
}
因此,为了解决这个位置问题(即 x 和 y,哦还有大小),我们可以使用一些好的旧 OOP 抽象。创建一个包含图像、位置和大小的类。例如
class LocatedImage {
private Image image;
private int x, y, width, height;
private ImageObserver observer;
public LocatedImage(Image image, int x, int y, int width,
int height, ImageObserver observer) {
this.image = image;
...
}
public void draw(Graphics2D g2d) {
g2d.drawImage(image, x, y, width, height, observer);
}
}
然后您可以在面板中使用此类的一堆实例。类似的东西
public class GamePanel extends JPanel {
List<LocatedImage> imagesToDraw;
// init images
// e.g. imagesToDraw.add(new LocatedImage(img, 20, 20, 100, 100, this));
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
for (LocatedImage image: imagesToDraw) {
image.draw(g2d);
}
g2d.dispose();
}
}
一旦你掌握了这个概念,就会有很多不同的可能性。
- 看看Performing Custom Painting有关绘画的一些一般想法。
关于java - JLabel 在另一个 JLabel 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26131977/