gpt4 book ai didi

Java 将图像从文件读取到 ArrayList 并显示到 JPanel 上

转载 作者:行者123 更新时间:2023-12-01 11:39:41 24 4
gpt4 key购买 nike

我正在尝试获取一个充满图像的文件并将它们读入 ArrayList 以制作一副卡片。然后将其显示在 JPanel 上。这是我的代码:

   private static class CardDealer extends JFrame 
{
private ImageIcon[] cards = new ImageIcon[52];
private ArrayList<ImageIcon> deck = new ArrayList<ImageIcon>();




private JButton deal;
private JPanel faceDown, faceUp, button;
private JLabel backs, fronts;
private Random card = new Random(52);


public CardDealer() throws FileNotFoundException
{

File images = new File("src/Images");
Scanner file = new Scanner(images);
for(int i=0; i<cards.length; i++)
{

cards[i] = new ImageIcon(Arrays.toString(images.list()));

deck.add(cards[i]);
}


//setTitle to set the title of the window

setTitle("Card Dealer");

//set the application to close on exit

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Call all our build panel methods
buildButtonPanel();
buildFaceDownPanel();
buildFaceUpPanel();

setLayout(new BorderLayout());

add(button, BorderLayout.SOUTH);
add(faceDown, BorderLayout.WEST);
add(faceUp, BorderLayout.EAST);

pack();

validate();

setVisible(true);
}

private void buildButtonPanel()
{
button = new JPanel();

deal = new JButton("Deal");

deal.addActionListener(new buttonListener());

button.add(deal);

}

private void buildFaceDownPanel()
{
faceDown = new JPanel();

backs = new JLabel();

backs.setText("Cards");

backs.setIcon(new ImageIcon("Blue.bmp"));



faceDown.add(backs);

}

private void buildFaceUpPanel()
{
faceUp = new JPanel();

fronts = new JLabel();

faceUp.add(fronts);
}

private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
fronts.setIcon(deck.get(card.nextInt()));
}
}

}


public static void main(String[] args) throws FileNotFoundException
{
new CardDealer();
}

我不知道为什么当我运行程序时没有图像显示。运行时甚至连背面的 JLabel 图像也不显示。如有任何帮助,我们将不胜感激!!

最佳答案

让我们从 File#list 开始,将返回包含在指定文件位置中的 File 对象数组,这使得

cards[i] = new ImageIcon(Arrays.toString(images.list()));

由于两个原因非常令人担忧,除了您只是将文件列表转换为 String 之外,这样做 cards.length 的效率非常低。 .

接下来,您不应该在代码中的任何路径中引用 src,一旦构建并打包,src 将不再存在,您将无法访问您的"file"就像普通文件一样(因为它们可能会嵌入到您的 jar 文件中)。

这引发了另一个问题,因为列出 jar 文件中嵌入的资源并不容易(当您甚至不知道 Jar 文件的名称时),您需要一种不同的方法。

一种可能是以常见的顺序方式命名图像,例如 /images/Card0.png/images/Card1.png,然后简单地通过循环加载图像

File images = new File("src/Images");
for(int i=0; i < cards.length; i++)
{
cards[i] = new ImageIcon(
ImageIO.read(
getClass().getResource("/images/Card" + i + ".png")));
deck.add(cards[i]);
}

看看Reading/Loading an Image有关读取/加载图像的更多详细信息

另一个解决方案可能是创建一个文本文件,该文件可以存储在应用程序上下文中,其中列出了所有卡名称。您可以使用 Class#getResourceClass#getResourceAsStream 加载文件,读取其内容并加载每个图像...

关于Java 将图像从文件读取到 ArrayList 并显示到 JPanel 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29641381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com