簡體   English   中英

嘗試運行JFrame時為什么會出現NullPointerException?

[英]Why am I getting a NullPointerException when I try to run my JFrame?

我知道這真的很簡單,但是由於我實例化了該類,所以我不明白為什么會收到此異常:

線程“主”中的異常java.lang.NullPointerException

在javax.swing.ImageIcon(ImageIcon.java:181)

在GameFrame(GameFrame.java:16)

在GameFrame.main(GameFrame.java:88)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GameFrame extends JFrame implements ActionListener{
    //Mini games and main panel components
    private JPanel MainPanel;
    private JPanel gamePanel1, gamePanel2, gamePanel3, gamePanel4, gamePanel5, gamePanel6, gamePanel7, gamePanel8, gamePanel9;
    private JPanel[] gamePanels = {gamePanel1, gamePanel2, gamePanel3, gamePanel4, gamePanel5, gamePanel6, gamePanel7, gamePanel8, gamePanel9};
    private JButton[][] buttons;
    private int turn;

    //X and O images
    private JLabel X = new JLabel();
    private ImageIcon x = new ImageIcon(getClass().getResource("/Images/X.PNG"));   
    private JLabel O = new JLabel();
    private ImageIcon o = new ImageIcon(getClass().getResource("/Images/O.PNG"));


    //constructor       
    public GameFrame() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        //gf.setSize(800,600);
        setVisible(true);

        setUpMainPanel();
        add(MainPanel);
    }

    public void setUpMainPanel() {
        //sets the layout
    }


    public static void main(String[] args) {
        GameFrame frame = new GameFrame();
    }
}

我已經嘗試在main()中執行所有構造函數的操作(例如setVisible(true)),但遇到相同的錯誤。 令人驚訝的是,關於此的信息不多。 為什么imageIcon給它帶來了問題? 感謝您的幫助!

我的猜測是您的應用程序找不到圖片。

你能加一個

System.out.println(getClass().getResource("/Images/X.PNG"));

並顯示結果? 我猜結果將顯示為“ null”。 如果是這樣,則圖像的位置不正確,例如,前斜杠可能是錯誤的,或者請注意文件或路徑的大小寫。

您可以嘗試以下

   BufferedImage image = ImageIO.read(getClass().getResource("/Images/X.PNG"));
   if(image != null)
       ImageIcon x = new ImageIcon(image);
   //X and O images
   private JLabel X = new JLabel();
   //try changing these around; EX:
   private ImageIcon x = new ImageIcon(getClass().getResource("X.PNG"));   
   private ImageIcon x = new ImageIcon(getClass().getResource("Images/X.PNG"));   
   private JLabel O = new JLabel();
   private ImageIcon o = new ImageIcon(getClass().getResource("previousFolder/Images/O.PNG"));

在“ /Images/X.PNG”位置沒有圖像。 將圖像“ X.PNG”放在/ Images目錄中

我最終放置

X = new JLabel();
x = new ImageIcon(getClass().getResource("/Images/X.PNG"));

O = new JLabel();
o = new ImageIcon(getClass().getResource("/Images/O.PNG"));

在里面

public void actionPerformed(ActionEvent e) {

暫無
暫無

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

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