簡體   English   中英

向Java項目添加資源

[英]Adding resources to a Java project

我正在嘗試向我的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();
 }
}

使用此代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM