如何使用JLabel将图片添加到JPanel

时间:2016-07-16 05:57:44

标签: java swing jpanel jlabel imageicon

当我尝试将我的图片图标添加到面板上的JLabel时,它根本不显示。谁能告诉我我做错了什么?这是我的代码的一部分:

    public class GameWindow extends JFrame implements ActionListener
{
    ImageIcon myPicture = new ImageIcon("src/GUI/Images/Face copy.png");
    JLabel picLabel = new JLabel(myPicture);

public GameWindow()

{
    super("Game Window");
    this.setSize(1500, 800);
    this.setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    JPanel tryThis = new JPanel();
    tryThis.setLayout(new BorderLayout());
    this.add(tryThis, BorderLayout.CENTER);
    JPanel grid1 = new JPanel();
    tryThis.add(grid1);

    int e = 4;
    int f = 14;
    JPanel[][] grid = new JPanel[e][f];
    grid1.setLayout(new GridLayout(e,f));

    for(int g = 0; g < e; g++) {
       for(int h = 0; h < f; h++) {
          grid[g][h] = new JPanel();
          grid1.add(grid[g][h]);
          grid[g][h].setBorder(BorderFactory.createTitledBorder("Info"));
       }
    }

    grid[3][3].add(picLabel);

1 个答案:

答案 0 :(得分:0)

好吧,我稍微调整了你的代码,但我设法让它在网格3,3上显示图像(虽然我只能在稍微调整屏幕大小后才能看到图像)

public class GameWindow extends JFrame implements ActionListener {

    public GameWindow(){
        super("Game Window");

        setSize(1500, 800);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel tryThis = new JPanel();
        tryThis.setLayout(new BorderLayout());

        add(tryThis, BorderLayout.CENTER);

        JPanel grid1 = new JPanel();
        tryThis.add(grid1);

        int e = 4;
        int f = 14;
        JPanel[][] grid = new JPanel[e][f];
        grid1.setLayout(new GridLayout(e,f));

        for(int g = 0; g < e; g++) {
           for(int h = 0; h < f; h++) {
              grid[g][h] = new JPanel();
              grid1.add(grid[g][h]);
              grid[g][h].setBorder(BorderFactory.createTitledBorder("Info"));
           }
        }

        try {
            // Loads the image
            BufferedImage myPicture = ImageIO.read(MainClassNameGoesHere.class.getResource("/example.png"));
            JLabel picLabel = new JLabel(new ImageIcon(myPicture));

            // Displays the image
            grid[3][3].add(picLabel);
        } catch (IOException exception) {
            exception.printStackTrace();
        }

    }

我改变的主要是你在图像中加载的方式。 我希望这会有所帮助,并随时提出任何问题。

相关问题