简体   繁体   English

无法将ImageIcon添加到JFrame

[英]Can't add ImageIcon to JFrame

I've been trying to add an image to a JFrame but I can't seem to get it done. 我一直在尝试将图像添加到JFrame但似乎无法完成。

I looked at online tutorials and other similar questions but nothing seems to work. 我看了在线教程和其他类似问题,但似乎没有任何效果。

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

I think the main problem in your program is that you try absolute positioning of components (eg JLabel ) using setLayout(null) and setBounds() on components. 我认为程序中的主要问题是您尝试在组件上使用setLayout(null)setBounds()来绝对定位组件(例如JLabel )。

In Swing, the correct way to place components is by using layout managers. 在Swing中,放置组件的正确方法是使用布局管理器。 See this tutorial for details about how to use layout managers: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html 有关如何使用布局管理器的详细信息,请参见本教程: https : //docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

As a sample program, I've successfully set images (both as JFrame 's icon and inside JFrame 's contents area) in below program. 作为一个示例程序,我已经在下面的程序中成功设置了图像(既是JFrame的图标,又位于JFrame的内容区域内)。 Try it and see. 试试看。

This is a screenshot of my sample 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);
  }
}

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

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