我試圖給我的JButton添加一個圖標,但我不斷收到一個NullPointerException,意思是我找不到指定的圖像。將資源添加到Java項目
我的類和buttonremoterefresh.png都直接在src文件夾內(類位於默認包內)。自昨晚以來,我一直在使用Google搜索,無論我嘗試什麼,我都無法加載資源。
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();
}
}
谷歌 「的getResourceAsStream」 ...... – vikingsteve
調用MainWindow.class.getResource( 「」)。的getPath(),並確認其中圖像被搜索的路徑。 – 2015-12-21 11:43:50