简体   繁体   English

将图像添加到数组JPanel

[英]Add images into an array JPanel

I have made a chessboard out of JPanel. 我已经用JPanel做了一个棋盘。 Using ImageIcon doesn't work, so I looked over the site, but all of it seems complicated, how do I add images to an array like 使用ImageIcon无效,因此我查看了该网站,但所有内容似乎都很复杂,如何将图像添加到数组中,例如

tiles[0][0].setIcon(br); 

This is the JPanel that I created for the chessboard 这是我为棋盘创建的JPanel

private JPanel[][] tiles = new JPanel[6][6];

I have tried this: 我已经试过了:

    ImageIcon bn = new ImageIcon("art/BN.gif");
    ImageIcon bb = new ImageIcon("art/BB.gif");
    ImageIcon br = new ImageIcon("art/BR.gif");
    ImageIcon wn = new ImageIcon("art/WN.gif");
    ImageIcon wb = new ImageIcon("art/WB.gif");
    ImageIcon wr = new ImageIcon("art/WR.gif");
    tiles[0][0].add(new JLabel(bn));
    tiles[0][1].add(new JLabel(wn));
    tiles[0][2].add(new JLabel(wb));
    tiles[0][3].add(new JLabel(wb));
    tiles[0][4].add(new JLabel(wn));
    tiles[0][5].add(new JLabel(wr));
    tiles[5][0].add(new JLabel(br));
    tiles[5][1].add(new JLabel(bn));
    tiles[5][2].add(new JLabel(bb));
    tiles[5][3].add(new JLabel(bb));
    tiles[5][4].add(new JLabel(bn));
    tiles[5][5].add(new JLabel(br));

But it doesn't work 但这不起作用

Where are your images being stored? 您的图像存储在哪里? What exactly doesn't work? 到底什么不起作用?

I'm going to take a shot in the dark and assume you're attempting to load files that are embedded in your application. 我将在黑暗中进行拍摄,并假设您正在尝试加载应用程序中嵌入的文件。

Taken from; 取自; https://docs.oracle.com/javase/7/docs/api/javax/swing/ImageIcon.html https://docs.oracle.com/javase/7/docs/api/javax/swing/ImageIcon.html

 ImageIcon(String filename) 

Creates an ImageIcon from the specified file. 从指定的文件创建一个ImageIcon。

 ImageIcon(URL location) 

Creates an ImageIcon from the specified URL. 从指定的URL创建一个ImageIcon。

Try this; 尝试这个;

ImageIcon bn = new ImageIcon(getClass().getResource("art/BN.gif"));

It will attempt to create an ImageIcon from a URL returned by .getResource() 它将尝试从.getResource()返回的URL创建ImageIcon。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM