我刚开始使用Java进行GUI编程,但是无法使用JFrame
将背景图像设置为JLabel
。我已经在这个网站上读到了很多关于同一问题的答案,但是对于初学者来说,代码太复杂了。
我的源代码如下,并且我正在使用的图像已经在src
文件夹中(我得到了输出窗口,但其中没有图像):
public class staffGUI extends JFrame {
private JLabel imageLabel = new JLabel(new ImageIcon("staff-directory.jpg"));
private JPanel bxPanel = new JPanel();
public staffGUI(){
super("Staff Management");
bxPanel.setLayout(new GridLayout(1,1));
bxPanel.add(imageLabel);
this.setLayout(new GridLayout(1,1));
this.add(bxPanel);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.pack();
}
最佳答案
ImageIcon(String)
“从指定文件创建ImageIcon”。实际的物理映像是在后台线程中加载的,因此即使调用可能立即返回,实际的加载仍可能在后台运行。
这意味着如果无法加载图像,ImageIcon
不会引发任何错误,有时会令人讨厌。我更喜欢在可能的地方使用ImageIO.read
,因为由于某种原因它无法读取图像时,它将抛出IOException
。
无法加载映像的原因是,该映像实际上不在JVM上下文中存在,而JVM上下文正在映像的当前工作目录中查找。
当您在程序的上下文中包含资源时,它们将不再被视为文件,而是需要根据需要通过使用Class#getResource
或Class#getResourceAsStream
进行加载。
例如
imageLabel = new JLabel(getClass().getResource("/staffdirectory/staff-directory.jpg"));
如果可能,应从源根目录的上下文中提供图像的路径
您能否举个例子,说明如何在代码中使用“ ImageIO.read”?
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class staffGUI extends JFrame {
private JLabel imageLabel;
private JPanel bxPanel = new JPanel();
public staffGUI() {
super("Staff Management");
imageLabel = new JLabel();
try {
BufferedImage img = ImageIO.read(getClass().getResource("/staffdirectory/staff-directory.jpg"));
imageLabel.setIcon(new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
bxPanel.setLayout(new GridLayout(1, 1));
bxPanel.add(imageLabel);
this.setLayout(new GridLayout(1, 1));
this.add(bxPanel);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.pack();
}
}