Java Can';t将ImageIcon添加到JFrame
我一直在尝试向Java Can';t将ImageIcon添加到JFrame,java,image,swing,embedded-resource,imageicon,Java,Image,Swing,Embedded Resource,Imageicon,我一直在尝试向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("Wi
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);
我认为您的程序中的主要问题是您尝试在组件上使用
setLayout(null)
和setBounds()
对组件进行绝对定位(例如JLabel
)
在Swing中,放置组件的正确方法是使用布局管理器。有关如何使用布局管理器的详细信息,请参见本教程:
作为一个示例程序,我已经成功地在下面的程序中设置了图像(作为JFrame
的图标和JFrame
的内容区域)。试试看
这是我的示例JFrame
的屏幕截图
我认为您的程序中的主要问题是您尝试在组件上使用
setLayout(null)
和setBounds()
对组件进行绝对定位(例如JLabel
)
在Swing中,放置组件的正确方法是使用布局管理器。有关如何使用布局管理器的详细信息,请参见本教程:
作为一个示例程序,我已经成功地在下面的程序中设置了图像(作为JFrame
的图标和JFrame
的内容区域)。试试看
这是我的示例JFrame
的屏幕截图
您向
JLabel
添加了一个ImageIcon
,但没有将该JLabel
添加到任何帧中。我刚刚添加了,但仍然没有显示任何内容。您是否设置了img1
的边界?是否与.setBounds()一起?是的,就像其他组件一样。您将一个ImageIcon
添加到JLabel
中,但不会将该JLabel
添加到任何帧中。我只是这样做了,但仍然没有显示任何内容。是否设置了img1
的边界?是否与.setBounds()一起?是的,就像其他组件一样。
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);
}
}