将图像添加到JLabel,并在GridLayout中显示标签

时间:2013-12-18 05:54:24

标签: java eclipse swing jlabel

我目前的代码,有趣地与另一个IDE(JGrasp)一起工作,虽然我目前正在尝试创建一个使用网络的游戏。 Eclipse允许在一台计算机上进行联网。出于某种原因,这个方法我发布了,它将想象添加到JLabel数组,不适用于eclipse?我是eclipse的新手,不知道为什么会这样?

private JPanel createBoard()
{
    // Instantiate Panel with a GridLayout
    board = new JPanel();
    board.setLayout(new GridLayout(10,10));

    // Fill the Panel with an Array of Labels
    // Checks for exception
    boardSpotArray = new JLabel[100];
    try
    {
        for (int x = 0; x < boardSpotArray.length; x++)
        {
            boardSpotArray[x] = new JLabel();
            boardSpotArray[x].setIcon(new ImageIcon(x + ".jpg"));
            board.add(boardSpotArray[x]);

        }
    }
    catch (IndexOutOfBoundsException exception)
    {
        System.out.println("Array drawer not available, " + exception.getMessage());
    }

    // return panel
    return board;
}

2 个答案:

答案 0 :(得分:1)

例如,如果boardSpotArray[0]"firstImage",则您的相对文件路径为"firstImage.jpg"。在Eclipse的这种情况下,并且不使用任何特殊的加载器或资源获取器,IDE将首先在项目根目录中查找映像。所以你的文件结构应该是这样的

ProjectRoot
         firstImage.jpg    <-- image as direct child of project root
         src
         bin

编辑:

如果您的图片位于src文件夹

ProjectRoot
        src
           0.jpg       <-- image in src
           1.jpg
           2.jpg

那么你的路径应该是这样的

new ImageIcon("src/" + x + ".jpg")

答案 1 :(得分:0)

Eclipse中的完整代码

import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class oo {
    public static JPanel createBoard()
    {
        // Instantiate Panel with a GridLayout
        JPanel board = new JPanel();
        board.setLayout(new GridLayout(10,10));

        // Fill the Panel with an Array of Labels
        // Checks for exception
        JLabel[] boardSpotArray = new JLabel[100];
        try
        {
            for (int x = 0; x < boardSpotArray.length; x++)
            {
                boardSpotArray[x] = new JLabel();
                boardSpotArray[x].setIcon(new ImageIcon("healthy-heart.jpg"));
                board.add(boardSpotArray[x]);

            }
        }
        catch (IndexOutOfBoundsException exception)
        {
            System.out.println("Array drawer not available, " + exception.getMessage());
        }

        // return panel
        return board;
    }
    public static void main(String[] args){
        JFrame frame=new JFrame();
        JPanel panel=createBoard();
        frame.getContentPane().add(panel);
        frame.setSize(100, 100);
        frame.pack();
        frame.setVisible(true);
    }
}

"healthy-heart.jpg"可以替换为任何其他图片。

相关问题