如何修复 try/catch Java NullPointerException
How to fix try/catch Java NullPointerException
我正在尝试按照 this 教程创建 2D 平台游戏。我创建了一个 Images()
-class ,如下所示:
包资源;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
public class Images {
public static BufferedImage[] tileBlocks;
public Images(){
tileBlocks = new BufferedImage[1];
try{
tileBlocks[0] = ImageIO.read(
// TODO: Fix the error caused by this try/catch
(Objects.requireNonNull(getClass().getResourceAsStream("TileBlocks/block_brick.png")))
);
} catch (IOException e) { e.printStackTrace(); }
}
}
我在 GamePanel()
-class 中创建了它的实例,看起来像这样
package Main;
import GameState.GameStateManager;
import Resources.Images;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.Serial;
@SuppressWarnings("BusyWait")
public class GamePanel extends JPanel implements Runnable, KeyListener {
@Serial
private static final long serialVersionUID = 1L;
// Game thread
private boolean isRunning = false;
int FPS = 60; // Frames per second
long targetTime = 1000 / FPS; // Set target time
// Set the dimension of the game-window
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
private GameStateManager gsm = new GameStateManager(); // Game state manager object
public GamePanel(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
addKeyListener(this);
setFocusable(true);
// TODO: Fix error (Reports instantiation of utility classes using the new keyword)
new Images();
start();
}
// Start the game (initialize)
private void start() {
isRunning = true;
Thread thread = new Thread(this); // Referring to Runnable
thread.start(); // Call to our game-loop
}
// Game-loop
public void run() {
long start, elapsed, wait; // Keep track of time
gsm = new GameStateManager(); // Initialize game state manager
while (isRunning) {
start = System.nanoTime(); // Start timer
update(); // Update the game-logic
repaint(); // Re-paint the board (built-in method from java.awt)
elapsed = System.nanoTime() - start;
// If everything runs in under the target time we wait (so it runs equally in all computers)
wait = targetTime - elapsed / 1000000; // Divide by 1 000 000 to get milli-seconds
if (wait <= 0) { wait = 5; } // Keep wait a positive value
try {
Thread.sleep(wait);
} catch (Exception e) { e.printStackTrace(); }
}
}
// Updating all game-logic
public void update() { gsm.update(); }// Call methods from game state manager in the game panel class
// Where we draw the graphics
public void paintComponent(Graphics g){
super.paintComponent(g); // Built-in method from java.awt
g.clearRect(0,0,WIDTH,HEIGHT); // Clear the screen before drawing
gsm.draw(g); // Call method from game state manager in the game panel class
}
public void keyPressed(KeyEvent e) {
gsm.keyPressed(e.getKeyCode()); // getKeyCode() turns KeyEvent into an integer
}
public void keyReleased(KeyEvent e) {
gsm.keyReleased(e.getKeyCode()); // getKeyCode() turns KeyEvent into an integer
}
public void keyTyped(KeyEvent e) { }
}
我收到一条错误消息
Instantiation of utility class 'Images'
Inspection info: Reports instantiation of utility classes using the new keyword.
In utility classes, all fields and methods are static.
Instantiation of such classes is most likely unnecessary and indicates a mistake.
当我尝试 运行 游戏时,它没有启动,我只得到 NullPointerException
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:208)
at inf112.skeleton.app/Resources.Images.<init>(Images.java:17)
at inf112.skeleton.app/Main.GamePanel.<init>(GamePanel.java:35)
at inf112.skeleton.app/Main.Game.game(Game.java:10)
at inf112.skeleton.app/Main.Game.main(Game.java:20)
但如果我删除实例化,游戏会启动,但随后会崩溃并出现更多错误
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException:
Cannot load from object array because "Resources.Images.tileBlocks" is null
etc...
如果我从中删除 Objects.requireNonNull
tileBlocks[0] = ImageIO.read((getClass().getResourceAsStream("TileBlocks/block_brick.png"))
游戏启动,但它崩溃了,我收到另一个错误提示
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException:
Cannot load from object array because "Resources.Images.tileBlocks" is null
我在这里做错了什么?为什么我的列表是tileBlocks null
?如何读取图像并将其显示在 tileBlocks
上?
将文件“block_brick.png”放入类路径中的目录“TileBlocks”中。
我正在尝试按照 this 教程创建 2D 平台游戏。我创建了一个 Images()
-class ,如下所示:
包资源;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
public class Images {
public static BufferedImage[] tileBlocks;
public Images(){
tileBlocks = new BufferedImage[1];
try{
tileBlocks[0] = ImageIO.read(
// TODO: Fix the error caused by this try/catch
(Objects.requireNonNull(getClass().getResourceAsStream("TileBlocks/block_brick.png")))
);
} catch (IOException e) { e.printStackTrace(); }
}
}
我在 GamePanel()
-class 中创建了它的实例,看起来像这样
package Main;
import GameState.GameStateManager;
import Resources.Images;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.Serial;
@SuppressWarnings("BusyWait")
public class GamePanel extends JPanel implements Runnable, KeyListener {
@Serial
private static final long serialVersionUID = 1L;
// Game thread
private boolean isRunning = false;
int FPS = 60; // Frames per second
long targetTime = 1000 / FPS; // Set target time
// Set the dimension of the game-window
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
private GameStateManager gsm = new GameStateManager(); // Game state manager object
public GamePanel(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
addKeyListener(this);
setFocusable(true);
// TODO: Fix error (Reports instantiation of utility classes using the new keyword)
new Images();
start();
}
// Start the game (initialize)
private void start() {
isRunning = true;
Thread thread = new Thread(this); // Referring to Runnable
thread.start(); // Call to our game-loop
}
// Game-loop
public void run() {
long start, elapsed, wait; // Keep track of time
gsm = new GameStateManager(); // Initialize game state manager
while (isRunning) {
start = System.nanoTime(); // Start timer
update(); // Update the game-logic
repaint(); // Re-paint the board (built-in method from java.awt)
elapsed = System.nanoTime() - start;
// If everything runs in under the target time we wait (so it runs equally in all computers)
wait = targetTime - elapsed / 1000000; // Divide by 1 000 000 to get milli-seconds
if (wait <= 0) { wait = 5; } // Keep wait a positive value
try {
Thread.sleep(wait);
} catch (Exception e) { e.printStackTrace(); }
}
}
// Updating all game-logic
public void update() { gsm.update(); }// Call methods from game state manager in the game panel class
// Where we draw the graphics
public void paintComponent(Graphics g){
super.paintComponent(g); // Built-in method from java.awt
g.clearRect(0,0,WIDTH,HEIGHT); // Clear the screen before drawing
gsm.draw(g); // Call method from game state manager in the game panel class
}
public void keyPressed(KeyEvent e) {
gsm.keyPressed(e.getKeyCode()); // getKeyCode() turns KeyEvent into an integer
}
public void keyReleased(KeyEvent e) {
gsm.keyReleased(e.getKeyCode()); // getKeyCode() turns KeyEvent into an integer
}
public void keyTyped(KeyEvent e) { }
}
我收到一条错误消息
Instantiation of utility class 'Images'
Inspection info: Reports instantiation of utility classes using the new keyword.
In utility classes, all fields and methods are static.
Instantiation of such classes is most likely unnecessary and indicates a mistake.
当我尝试 运行 游戏时,它没有启动,我只得到 NullPointerException
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:208)
at inf112.skeleton.app/Resources.Images.<init>(Images.java:17)
at inf112.skeleton.app/Main.GamePanel.<init>(GamePanel.java:35)
at inf112.skeleton.app/Main.Game.game(Game.java:10)
at inf112.skeleton.app/Main.Game.main(Game.java:20)
但如果我删除实例化,游戏会启动,但随后会崩溃并出现更多错误
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException:
Cannot load from object array because "Resources.Images.tileBlocks" is null
etc...
如果我从中删除 Objects.requireNonNull
tileBlocks[0] = ImageIO.read((getClass().getResourceAsStream("TileBlocks/block_brick.png"))
游戏启动,但它崩溃了,我收到另一个错误提示
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException:
Cannot load from object array because "Resources.Images.tileBlocks" is null
我在这里做错了什么?为什么我的列表是tileBlocks null
?如何读取图像并将其显示在 tileBlocks
上?
将文件“block_brick.png”放入类路径中的目录“TileBlocks”中。