gpt4 book ai didi

java - 使用 ImageIcon 和 JLabel

转载 作者:行者123 更新时间:2023-11-29 06:11:30 25 4
gpt4 key购买 nike

我的目标是拥有一个 imageIcon 并将其添加到一个 JLabel 中,这样它就会出现在我的 GUI 上。到目前为止我的代码是:

package classes;

import javax.swing.*;

public class Picture extends JFrame {

private ImageIcon _image1;
private JLabel _mainLabel;

public Picture(){
_image1 = new ImageIcon("picture1.jpg");
_mainLabel = new JLabel(_image1);
add(_mainLabel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

package classes;

public class Driver {
public static void main(String[] args) {
Picture p = new Picture();
}
}

问题是图片没有出现在我的 GUI 上。如果有人有任何建议,请告诉我,谢谢!

最佳答案

您确定 Java 正在寻找 picture1.jpg 文件的正确位置吗?该文件是否位于当前工作目录中?

将此代码放在程序中的某个位置,以便在程序运行时调用它:

// show the current working directory
System.out.println("current working directory is: " + System.getProperty("user.dir"));

返回的字符串将告诉您 Java 正在查找的位置,以及您当前的工作目录所在的位置。然后您可以使用该信息来调整您的路径,或者您始终可以只使用图像文件的完整路径。

编辑:
此外,不要忘记打包您的 JFrame,以便它会相应地布局组件和调整自身大小:

   public Picture() {

_image1 = new ImageIcon(IMAGE);
_mainLabel = new JLabel(_image1);
add(_mainLabel);

pack(); // to tell the layout managers to set up the GUI
setLocationRelativeTo(null); // center things
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

关于java - 使用 ImageIcon 和 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6673833/

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