2

这是主要课程

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)
4

3 回答 3

2

where have you initialized Graphics2D object 'g' , you should properly initialize it.

于 2013-08-21T19:22:09.197 回答
2
  • 不需要调用 as 之类的东西PaintComponents(g);,删除此代码行,没用

  • 绘画在没有更多的Swing完成,在这里搜索标记为的问题 paintComponent()PaintComponents()Oracle tutorial Working with ImagespaintComponent()

  • JPanel那么ImageObserver应该 g.drawImage(image, 0,0,null);g.drawImage(image, 0, 0, this);

  • new testing();应该被包裹起来invokeLater,更多的看到Oracle tutorial Initial Thread

  • 不要setSize(800,600);从 JFramegetPreferredSize覆盖public class Canvas extends JPanel {

  • public class testing extends JFrame{

    1. 应该public class Testing {

    2. 创建JFrame为局部变量(类似于BufferedImage image;

编辑。像

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);
    }
};
于 2013-08-21T19:31:35.227 回答
0

二维图形

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

由于Graphics2D是一个抽象类,而且必须为不同的输出设备通过子类定制,所以不能直接创建Graphics2D对象。相反,Graphics2D 对象必须从另一个 Graphics2D 对象获得,由组件创建,或从图像(如 BufferedImage 对象)获得。

利用:

Graphics2D g2 = (Graphics2D)g;
g2.drawImage();
于 2013-08-21T19:23:15.263 回答