【问题标题】:How can I display several images from within a for loop如何在 for 循环中显示多个图像
【发布时间】:2012-05-25 01:33:19
【问题描述】:

为了学校,我需要做一个游戏,随机发 [X] 张牌。 我使用此代码来构建和显示我的图像。 只有一件事出错了。显示项目时,只有最后一张卡片 显示。

有什么方法可以让这些图片并排显示?

public static void main(String[] args) throws FileNotFoundException, IOException {
    Cards cards = new Cards();
    int dealSize = 6;
    deal = cards.getShuffledCards(dealSize);
    System.out.println("Deal of 4 randomly picked cards " + deal);
    f = new JFrame();
    for(int i=0; i < dealSize; i++) {
        card = deal.get(i).toString();
        f.getContentPane().add(setLabel(card));
    }
    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocation(200,200);
    f.setVisible(true);



}

public static JLabel setLabel(String fileLocation) throws FileNotFoundException, IOException {
    InputStream file = new BufferedInputStream(
        new FileInputStream([DIRECTORY TO IMAGES]" + fileLocation));
        BufferedImage image = ImageIO.read(file);
        label = new JLabel(new ImageIcon(image));
        return label;

}

【问题讨论】:

    标签: java image for-loop


    【解决方案1】:

    您可能必须制作一个任意网格,其中一张卡片可以占据每个部分。类似于 GridLayout 或 GridBagLayout。

    从我通过浏览您的代码可以看出,您基本上是在为每次迭代覆盖您放置的最后一个元素。

    【讨论】:

    • 这也是我害怕的。但我真的不知道如何动态添加图片
    • 正如我所说,尝试不同的布局。就像一个 GridLayout。如果允许,您可以在 NetBeans 等 GUI 构建器中轻松进行设置。
    猜你喜欢
    • 2011-12-07
    • 2019-10-08
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2019-09-07
    • 2021-07-09
    相关资源
    最近更新 更多