将图像添加到数组JPanel中

时间:2016-10-02 10:41:57

标签: java image jpanel

我用JPanel制作了一个棋盘。使用ImageIcon不起作用,所以我查看了网站,但所有这些看起来都很复杂,如何将图像添加到数组中,如

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

这是我为棋盘创建的JPanel

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

我试过这个:

    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));

但它不起作用

1 个答案:

答案 0 :(得分:0)

您的图片存储在哪里?究竟什么不起作用?

我将在黑暗中拍摄,并假设您正在尝试加载应用程序中嵌入的文件。

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

ImageIcon(String filename)
     

从指定文件创建ImageIcon。

ImageIcon(URL location)
     

从指定的URL创建ImageIcon。

试试这个;

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

它将尝试从.getResource()

返回的URL创建ImageIcon
相关问题