【问题标题】:Can't add ImageIcon to JFrame无法将 ImageIcon 添加到 JFrame
【发布时间】:2019-06-06 22:12:21
【问题描述】:

我一直在尝试将图像添加到 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);

【问题讨论】:

  • 您将ImageIcon 添加到JLabel,但您没有将JLabel 添加到任何帧。
  • 我只是这样做了,但仍然没有出现
  • 你设置img1的边界了吗?
  • 那会是 .setBounds() 吗?
  • 是的,就像其他组件一样。

标签: java image swing embedded-resource imageicon


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 2012-12-26
    相关资源
    最近更新 更多