首页 > 解决方案 > 无法将 ImageIcon 添加到 JFrame

问题描述

我一直在尝试向 a 添加图像,JFrame但似乎无法完成。

我查看了在线教程和其他类似问题,但似乎没有任何效果。

ImageIcon wiz = new ImageIcon("wizard.png");
ImageIcon assassin = new ImageIcon("assassin.png");

JFrame frame = new JFrame("Select");
frame.setBounds(50, 50,1000, 1000);
JButton w = new JButton("Wizard");
JButton a = new JButton("Assasin");

JFrame f = new JFrame("Image");

JLabel img1 = new JLabel(wiz);

frame.setLayout(null);
f.setLayout(null);
f.setIconImage(wiz.getImage());

w.setBounds(30,380,100,60);
frame.add(w);

a.setBounds(200, 380, 100, 60);
frame.add(a);

f.setVisible(true);
frame.setVisible(true);

标签: javaimageswingembedded-resourceimageicon

解决方案


我认为您程序中的主要问题是您尝试使用和在组件上对组件(例如JLabel)进行绝对定位。setLayout(null)setBounds()

在 Swing 中,放置组件的正确方法是使用布局管理器。有关如何使用布局管理器的详细信息,请参阅本教程: https ://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

作为一个示例程序,我已经在下面的程序中成功地设置了图像(作为JFrame' 图标和内部JFrame' 内容区域)。试试看。

这是我的示例的屏幕截图JFrame

在此处输入图像描述

import javax.swing.*;

public class FrameWithIcon
{
  public static void main(String[] args)
  {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Since I'm not setting a layout manager to contentPane, it's default (BorderLayout) is used

    //This sets the image in JFrame's content area
    f.getContentPane().add(new JLabel(new ImageIcon("star.png")));

    //This sets JFrame's icon (shown in top left corner of JFrame)
    f.setIconImage(new ImageIcon("star.png").getImage());

    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}

推荐阅读