gpt4 book ai didi

Java 组合框 + 图像图标

转载 作者:行者123 更新时间:2023-12-02 08:14:30 24 4
gpt4 key购买 nike

我正在尝试构建一个非常基本的程序,该程序将根据下拉框中选择的项目在两张图片之间交替。这是我尝试运行的代码,但我不断收到错误消息:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at Gui.<init>(Gui.java:10)
at Apples.main(Apples.java:7)

图像位于 src 文件中。

有人知道我做错了什么吗?谢谢,拉文

this screenshot demonstrates that the images are in the src file

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Gui extends JFrame{

private JComboBox box;
private JLabel picture;
private static String [] filename = {"Ravinsface.png", "Wojs face.png"};
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};

public Gui(){
super("The Title");
setLayout(new FlowLayout());
box = new JComboBox(filename);
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED);
picture.setIcon(pics[box.getSelectedIndex()]);

}
}

);
add(box);
picture = new JLabel(pics[1]);
add(picture);


}

}

最佳答案

使用 getClass().getClassLoader().getResource(String)

/e1 我在另一个答案中解释了不同的 getResource(String) 方法。

关于Java 组合框 + 图像图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6711095/

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