水平堆叠卡片有一些偏移量

时间:2015-08-26 04:45:02

标签: java swing

如何堆叠(卡片)图像:

enter image description here

这是我到目前为止所显示的,显然我正在尝试设置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);

                }

            }

2 个答案:

答案 0 :(得分:2)

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

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

当然,您还需要更新x坐标以从左到右错开它们。 见https://docs.oracle.com/javase/tutorial/uiswing/layout/none.html

答案 1 :(得分:0)

我最终做到了这样,对我来说效果很好。

    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;

            }

        }

因此输出是:

enter image description here