有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JLabel超过另一个JLabel不工作

我一直在试着为我的流氓形象换一个。不幸的是,它似乎不起作用。以下是我目前的代码:

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


共 (1) 个答案

  1. # 1 楼答案

    一种选择

    不要使用组件(如JLabel)创建游戏环境。相反,您可以绘制所有游戏对象

    例如,如果你正在做以下事情:

    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();
        }  
    }
    

    一旦你有了这个概念,就会有很多不同的可能性