有没有更好的方法来添加大量的JPanels与附加到阵列的独特图像?

时间:2015-02-12 01:29:52

标签: java swing jpanel

我有一整套卡片作为我需要的图像: a)加载JPanels和 b)在JFrame中显示。

是否有更好的方法让他们进入我的程序然后一遍又一遍地(52x)编写像

这样的东西
final JPanel panelName = draw(new ImageIcon("spritesheet.gif"));

每个图像(spritesheet.gif)都有一个唯一的名称。这是一副纸牌。

以下是draw

public static JPanel draw(final ImageIcon img)
{
    JPanel panel = new JPanel()
    {
        private static final long serialVersionUID = 1L;

        //paintComponent is called automatically by the JRE whenever
        //the panel needs to be drawn or redrawn
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            img.paintIcon(this, g, 10, 10);
            }
    };
    panel.setOpaque(false);
    return panel;
}

1 个答案:

答案 0 :(得分:4)

  

每张图片都有一个唯一的名称..

只要有某种模式,就可以轻松实现。例如。 "spades-queen.gif"可以来自诉讼数组String[],等级数组-来分隔它们&最后一个.gif ..

  

他们的格式设置为aceSpades,依此类推。

这是一个实现:

public class CardNames {
    public final static String[] SUITS = {
        "Spades", "Hearts", "Diamonds", "Clubs"
    };
    public final static String[] LEVELS = {
        "ace", "two", "three", "four", "five", "six", "seven", "eight", "nine",
        "ten", "jack", "queen", "king"
    };
    public final static String SEP = "";
    public final static String XTN = ".gif";

    public static void main(String[] args) {
        for (String suit : SUITS) {
            for (String level : LEVELS) {
                System.out.println(level + SEP + suit + XTN);
            }
        }
    }
}

输出

aceSpades.gif
twoSpades.gif
threeSpades.gif
fourSpades.gif
fiveSpades.gif
sixSpades.gif
sevenSpades.gif
eightSpades.gif
nineSpades.gif
tenSpades.gif
jackSpades.gif
queenSpades.gif
kingSpades.gif
aceHearts.gif
// ...
aceClubs.gif
twoClubs.gif
threeClubs.gif
fourClubs.gif
fiveClubs.gif
sixClubs.gif
sevenClubs.gif
eightClubs.gif
nineClubs.gif
tenClubs.gif
jackClubs.gif
queenClubs.gif
kingClubs.gif