2015-12-21 121 views
1

我試圖給我的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(); 
} 
} 
+0

谷歌 「的getResourceAsStream」 ...... – vikingsteve

+0

調用MainWindow.class.getResource( 「」)。的getPath(),並確認其中圖像被搜索的路徑。 – 2015-12-21 11:43:50

回答

0

使用此代碼

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

它已經工作,非常感謝。我仍然不確定舊代碼的問題。 java是否需要在每個資源上打開一個流? –

+0

這裏我使用imageicon insted圖像 –

相關問題