JLabel在另一个JLabel上不起作用 [英] JLabel over another JLabel not working

查看:70
本文介绍了JLabel在另一个JLabel上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为我的Roguelike尝试将JLabel放在另一个JLabel上.不幸的是,它似乎不起作用.到目前为止,这是我的代码:

I've been trying to put a JLabel over another one for my Roguelike. Unfortunaly, it doesn't seems to work. Here's my code so far :

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添加到另一个解决方案来完成的.它不按这里的预期工作,不知道为什么吗?

I've read some solutions to other problems, and they all do it by simply adding the JLabel to the other one. it doesn't work as intended here, any idea why ?

PS:我不想为我的JPanel使用JLayeredPane.

PS : I don't want to use a JLayeredPane for my JPanel.

推荐答案

一个替代方案

请勿使用组件(即JLabels)创建游戏环境.相反,您可以绘制所有游戏对象.

One Alternative

Don't create your game environment using components (i.e. JLabels). Instead, you can paint all your game objects.

例如,如果您正在执行以下操作:

For instance, if you're doing something like:

JLabel[][] labelGrid = JLabel[][];
...
ImageIcon icon = new ImageIcon(...);
JLabel label = new JLabel(icon);
...
for(... ; ... ; ...) {
   container.add(label);
}

您可以改掉所有标签,也可以使用Images代替ImageIcons,然后可以将所有图像绘制到单个组件表面.也许像这样:

You could instead get rid of the labels all together, and also use Images instead of ImageIcons, then you can just paint all the images to a single component surface. Maybe something like:

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 */);
    }  
}

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆