我曾尝试在面板上使用 ImageIcon 绘图和图像方式,我曾尝试使用 ImageIO.read 绘图方式,我已经构建和重建多个项目,每次我收到错误消息:
Exception in thread "main" java.lang.NullPointerException
at Image_Test.screen.draw(screen.java:41)
at Image_Test.Basic.run(Basic.java:23)
at Image_Test.Basic.main(Basic.java:16)
screen.java:41 是与此确切代码的一行:
g.drawImage(test, 100, 100, null);
我看过 4 或 5 个不同作者的教程,所有这些教程都使用 null 作为该方法中的最后一个参数。这是我的整个 Basic 类(具有 main 方法)以及我的 screen 类(具有 drawImage 方法)的副本。这是项目中仅有的两个类。
package Image_Test;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class Basic
{
public JFrame window;
public String title = "The Title for This Window";
public screen screen = new screen();
public Graphics g;
public static void main(String[] args) { new Basic().run(); }
// The run() method is pretty much the main method
public void run ()
{
buildWindow();
screen.draw(g);
}
public void buildWindow ()
{
window = new JFrame(title);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(screen, BorderLayout.CENTER);
window.setSize(1366, 768);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation(dim.width/2-window.getSize().width/2, dim.height/2-window.getSize().height/2);
window.setVisible(true);
}
}
package Full_Game_Test_02;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
public class screen extends JPanel
{
public Image Start_Idle;
public Image Start_Active;
public Image Exit_Idle;
public Image Exit_Active;
Image test = null;
public screen ()
{
test = screen.loadImage("/Start_Active.png");
}
public void loadImages ()
{
Start_Active = new ImageIcon("C:\\Developing\\Start_Active").getImage();
Exit_Idle = new ImageIcon("C:\\Developing\\End_Idle").getImage();
Exit_Active = new ImageIcon("C:\\Developing\\End_Active").getImage();
}
public void draw (Graphics g)
{
g.drawImage(test, 100, 100, null);
}
public static Image loadImage (String file)
{
Image image = null;
// Exception 1
try
{
image = ImageIO.read(screen.class.getResource(file));
}
catch (Exception e1)
{
System.out.println("Exception 1");
}
return image;
}
}