在图像加载之前是paintComponent绘画,如果是,我该如何修复它?

时间:2016-06-12 04:59:44

标签: java image swing nullpointerexception paintcomponent

我正在设计像游戏一样的cookie点击器。我有一个扩展JPanel的类,在构造函数中我将一些图像加载到Image对象中。但是当我在paintComponent中绘制它们时,控制台开始喷出NullPointerExceptions几秒钟然后停止并且窗口正确加载。我唯一的猜测是图像需要时间来加载,而paintComponent试图在它们完全加载之前绘制它们。任何帮助表示赞赏。感谢。

public PanelClass() {
        frame.setSize(screenSize);
        frame.add(this);
        frame.setUndecorated(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        addMouseListener(this);
        addMouseMotionListener(this);
            buttonGraphics.start();
        try {
            background = ImageIO.read(new File("res/img/Background.png")).getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
            steamLogo[0] = ImageIO.read(new File("res/img/SteamLogo.png")).getScaledInstance(getWidth()/5, getWidth()/5, Image.SCALE_SMOOTH);
            for (int i = 1; i < steamLogo.length; i++) {
                steamLogo[i] = steamLogo[0].getScaledInstance(steamLogo[0].getWidth(null)-(i*2), steamLogo[0].getWidth(null)-(i*2), Image.SCALE_SMOOTH);
            }       
        } catch (IOException e) {
            e.printStackTrace();
        }
        logoHitbox = new Ellipse2D.Double((getWidth()/2)-(steamLogo[0].getWidth(null)/2), (getHeight()/2)-(steamLogo[0].getHeight(null)/2), getWidth()/5, getWidth()/5);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(background, 0, 0, null);
        g.drawImage(steamLogo[curLogo], (getWidth()/2)-(steamLogo[curLogo].getWidth(null)/2), (getHeight()/2)-(steamLogo[curLogo].getHeight(null)/2), null);
        if(clicked > 1) {
            g.setColor(new Color(0,0,0,155-(clicked*7)));
            g.fillOval((getWidth()/2)-(steamLogo[curLogo].getWidth(null)/2), (getHeight()/2)-(steamLogo[curLogo].getHeight(null)/2), (int)steamLogo[curLogo].getWidth(null), (int)steamLogo[curLogo].getHeight(null));
        }
    }

0 个答案:

没有答案