Java 以一定的偏移量水平堆叠卡片

Java 以一定的偏移量水平堆叠卡片,java,swing,Java,Swing,我如何像这样堆叠(卡片的)图像: 这就是我到目前为止所拥有的,显然我正在尝试设置JLabel cardIcon的位置,每次我猜它都会被替换 JPanel tableMat = new JPanel(); for (CardSet card : playersHand) { String path = dirPath + card.suit().toString()+"-"+card.rank().toString()+".gi

我如何像这样堆叠(卡片的)图像:

这就是我到目前为止所拥有的,显然我正在尝试设置JLabel cardIcon的位置,每次我猜它都会被替换

    JPanel tableMat = new JPanel();

            for (CardSet card : playersHand) {

                String path = dirPath + card.suit().toString()+"-"+card.rank().toString()+".gif";
                File file = new File(path);

                if (!file.exists()) {
                    System.out.println(path);
                    throw new IllegalArgumentException("file " + file + " does not exist");


                } else {
                    BufferedImage icon = ImageIO.read(new File(file.getAbsolutePath()));
                    JLabel cardIcon = new JLabel(new ImageIcon(icon));
                    cardIcon.setLocation(300,300);
                    tableMat.add(cardIcon);

                }

            }

tableMat=new JPanel()
使用默认的FlowLayout对其进行初始化,因此
cardIcon.setLocation(300300)
将被忽略-当调用
tableMat.add(cardIcon)
时,布局管理器将决定位置

您需要从tableMat中删除布局管理器,例如
tableMat=new JPanel(null)

当然,您还需要更新x坐标以使其从左到右错开。

我最后就是这样做的,而且对我来说效果很好

    JLayeredPane tableMat = new JLayeredPane();
        int i =0;
        int x_offset = 15;
        for (CardSet card : playersHand) {

            String path = dirPath + card.suit().toString()+"-"+card.rank().toString()+".gif";
            File file = new File(path);

            if (!file.exists()) {
                System.out.println(path);
                throw new IllegalArgumentException("file " + file + " does not exist");


            } else {
                BufferedImage icon = ImageIO.read(new File(file.getAbsolutePath()));
                JLabel cardIcon = new JLabel(new ImageIcon(icon));
                cardIcon.setBounds(x_offset,20,300,300);
                tableMat.add(cardIcon, new Integer(i));
                i++;
                x_offset += 15;

            }

        }
因此,输出为:


乍一看,cardIcon.setLocation()似乎在将所有卡设置到同一位置。实际上,它甚至没有这样做。它现在所做的就是从位置0,0开始放置卡片,然后像流程布局一样一张接一张地放置卡片。