有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

向Java项目添加资源

我试图在我的JButton中添加一个图标,但我一直得到一个NullPointerException,这意味着找不到我指定的图像

我的课程和按钮都是远程刷新。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) 个答案

  1. # 1 楼答案

    使用这个代码

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