我正在編寫一個程序,要求我有一個帶有超過它的圖像的按鈕,但到目前爲止,我還沒有能夠得到它的工作。我檢查了這個網站上的其他幾個帖子,包括How do I add an image to a JButton。
我的代碼:如何把圖像放在JButton上?
public class Tester extends JFrame
{
public Tester()
{
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
setTitle("Image Test");
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button = new JButton();
try
{
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
button.setIcon(new ImageIcon(img));
}
catch (IOException ex) {}
button.setBounds(100,100,100,100);
panel.add(button);
}
public static void main(String[] args)
{
Tester test = new Tester();
test.setVisible(true);
}
}
運行此代碼時,將導致錯誤:異常在線程 「主」 java.lang.IllegalArgumentException異常:輸入== NULL!在該行出現此錯誤:
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
我不認爲這個錯誤是由於不被Java代碼中找到的文件,我的圖片文件夾是src文件夾中(我使用Eclipse)作爲通過上面的鏈接推薦。
有沒有人有什麼想法可能是什麼問題?
謝謝。
請提供您的項目層次結構中的圖像路徑 – CAMOBAP
您是否真的檢查過'getResource()'的返回值? – vstm
這是圖像路徑:C:\ Documents and Settings \ student \ My Documents \ Dropbox \ ADVCS_Workspace \ Chess_Program \ src \ Images –