gpt4 book ai didi

java - 需要使用 JLabel 设置背景图像的帮助吗?

转载 作者:行者123 更新时间:2023-12-01 11:46:37 25 4
gpt4 key购买 nike

我刚刚开始使用 Java 进行 GUI 编程,但在使用 JLabel 将背景图像设置为 JFrame 时遇到问题。我在这个网站上阅读了同一问题的许多答案,但代码对于初学者来说太复杂了。

我的源代码如下,我正在使用的图像已经在 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"));

如果可能,您应该从源根目录的上下文中提供图像的路径

Can you give an example how I can use the "ImageIO.read" in my code?

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

}
}

关于java - 需要使用 JLabel 设置背景图像的帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29091541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com