gpt4 book ai didi

java - 向 Java 项目添加资源

转载 作者:太空宇宙 更新时间:2023-11-04 13:06:16 25 4
gpt4 key购买 nike

我正在尝试向 JButton 添加图标,但我不断收到 NullPointerException,这意味着无法找到我指定的图像。

我的类和buttonremoterefresh.png都直接位于src文件夹内(这些类位于默认包内)。从昨晚开始我一直在谷歌上搜索这个问题,无论我尝试什么,我都无法加载资源。

public class InfiltratorClient {

private MainWindow mw;

public static void main(String[] args) {
new InfiltratorClient();
}

public InfiltratorClient () {
mw = new MainWindow();
}
}


public class MainWindow extends JFrame {

private JPanel contentPane;
private InfiltratorClient n;


public MainWindow() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
this.setSize(650, 600);
setVisible(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(258, 228, 140, 105);
contentPane.add(btnNewButton);

//In this Line i get the exception
ImageIcon icon = new ImageIcon(MainWindow.class.getResource("buttonremorerefresh.png"));
btnNewButton.setIcon(icon);

repaint();
revalidate();
}
}

最佳答案

使用此代码

 JButton button = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("buttonremorerefresh.png"));
button.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}

关于java - 向 Java 项目添加资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34394562/

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