向Java项目添加资源

时间:2015-12-21 11:25:24

标签: java

我试图在我的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();
 }
}

1 个答案:

答案 0 :(得分:0)

使用此代码

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