什么叫paintComponent()?

黑暗之物

我正在尝试从子图形表中绘制子图形。

我有以下课程

public class GTComponent extends JComponent {

    Graphics2D g2;

    @Override
    public void paintComponent(Graphics g){
        g2 = (Graphics2D)g;
    }

    public void drawSpriteFrame(Image source, int x, int y, int frame) {
        int frameX = (frame % 12) * 32;
        int frameY = (frame / 12) * 32;
        g2.drawImage(source, x, y, x + 32, y + 32,
                frameX, frameY, frameX + 32, frameY + 32, this);
    }
}

这样就在主类中将其创建为对象

    JFrame f = new JFrame();
    GTComponent img = new GTComponent();

    f.add(img);

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize((int)(i.length * 8.1), (int)(i[0].length * 8.5));
    f.setVisible(true);
    f.setLocationRelativeTo(null);

    BufferedImage test = null;
    try {
        test = ImageIO.read(new File( /*Image File path*/));
    }
    catch (IOException e) {
        System.out.println("error");
        System.exit(0);
    }

    img.drawSpriteFrame(test, (u * 32 + 1), (z * 32 + 1), c);

我面临的问题是抛出以下错误

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

经过几次调试后,在paintComponent处设置断点drawSpriteFrame,我发现该drawSpriteFrame方法在该paintComponent方法之前被调用,这意味着g2 = null导致抛出该错误。

这里的问题是什么触发允许我初始化g2变量的paintComponent方法?

戴维·摩尔

paintComponent()从事件调度线程自动调用的如果希望将自定义组件作为普通的Swing绘画过程的一部分进行绘画,则应重写paintComponent()以调用您的drawSpriteFrame()方法,而不是drawSpriteFrame()直接调用

如果要自己控制绘图操作,则需要使用“全屏独占模式”教程中所述的“活动渲染” 请注意,此处描述的技术也适用于窗口应用程序。基本上,您需要向窗口询问Graphics实例(而不是等待实例传递到实例paintComponent()然后再绘制实例)

使用双缓冲的基本示例:

// Initial setup
Frame mainFrame = new Frame();
mainFrame.setVisible(true); // you'll also want to set size, location, etc.
mainFrame.createBufferStrategy(2);
BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();

//.... 

// Inside your draw loop (call once for each frame)
Graphics2D g2 = (Graphics2D) bufferStrategy.getDrawGraphics();
g2.drawImage(...) // etc.
g2.dispose();
bufferStrategy.show();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章