继续得到nullpointerException?我正在尝试打印出图像

时间:2013-08-21 19:17:05

标签: java image swing graphics

这是主要的课程

public class Testing extends JFrame{

private static final long serialVersionUID = 1L;

public Testing(){
    setContentPane(new Canvas());
    setVisible(true);
    setLocationRelativeTo(null);

}
public static void main(String[] args0){
    new Testing();
}

}

并且Canvas类中的错误发生在drawImage方法中。我已经创建了一个res文件夹,我将其放入我的图像并将其用作源文件夹。

public class Canvas extends JPanel{
Graphics g;
Graphics2D g2 = (Graphics2D)g;
BufferedImage image;
private static final long serialVersionUID = 1L;
public Canvas(){
    setPreferredSize(new Dimension(800,600));
    loadImage("/space.png");
    draw(g2);
}
public void draw(Graphics2D g2){
    g2.drawImage(image, 0,0,this);
}
public void loadImage(String path){
    try {
        image = ImageIO.read(
            getClass().getResourceAsStream(path)
        );
    }
    catch(Exception e) {
        e.printStackTrace();
        System.out.println("image loading error");
    }

}

}

感谢您的帮助。

我运行程序时遇到的错误。

Exception in thread "main" java.lang.NullPointerException
at Canvas.draw(Canvas.java:21)
at Canvas.<init>(Canvas.java:18)
at Testing.<init>(Testing.java:11)
at Testing.main(Testing.java:17)

3 个答案:

答案 0 :(得分:2)

你在哪里初始化了Graphics2D对象'g',你应该正确初始化它。

答案 1 :(得分:2)

  • 不需要调用PaintComponents(g);之类的内容,删除此代码行,无用

  • Swing中的绘画已在paintComponent() PaintComponents()paintComponent()更多JPanel完成,请在此处搜索由ImageObserver标记的问题

  • g.drawImage(image, 0,0,null);g.drawImage(image, 0, 0, this);new testing();应为invokeLater

  • setSize(800,600);应该包含在getPreferredSize中,更多信息请参见Oracle tutorial Working with Images

  • 请{J}自public class Canvas extends JPanel {覆盖public class testing extends JFrame{中的public class Testing {

  • JFrame

    1. 应为BufferedImage image;

    2. 创建JPanel panel = new JPanel() { private static final long serialVersionUID = 1L; private Image image = new ImageIcon("Images/mong.jpg").getImage(); @Override public Dimension getPreferredSize() { return new Dimension(800, 600); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, getWidth(), getHeight(), this); } }; 作为局部变量(similair为{{1}})

EDIT。类似于

的东西
{{1}}

答案 2 :(得分:0)

<强> Graphics2D

  

protected Graphics2D()构造一个新的Graphics2D对象。

     

由于Graphics2D是一个抽象类,因为它必须通过自定义   不同输出设备的子类,Graphics2D对象不能   直接创建。相反,必须从中获取Graphics2D对象   另一个Graphics2D对象,由Component创建或从中获取   像BufferedImage对象的图像。

使用:

Graphics2D g2 = (Graphics2D)g;
g2.drawImage();
相关问题