getGraphics()返回null值

时间:2017-01-22 17:37:52

标签: java swing user-interface drawing

JPanel预览在getGraphics()方法中调用drawToScreen后返回null。 Test类确实扩展了JPanel,因为它保持在TabbedPane范围内。该类还实现了RunnableKeyListenerMouseListener

log的{​​{1}}是

  

javax.swing.JPanel中[,172,149,1280x720,布局= java.awt.FlowLayout中,alignmentX = 0.0,alignmentY = 0.0,边界=,旗帜= 9,MAXIMUMSIZE =,=的minimumSize,首选大小=空]

以下是现有代码的示例。运行它将无法工作,因为它使用外部方法来完成自己,但希望可以找到答案。

System.out.println

至于其余代码,根据markspace的请求,我已将其余部分添加到提供样本之外的debunk中。

public Test() {

    setBackground(Color.DARK_GRAY);
    setLayout(null);

    preview = new JPanel();
    preview.setBounds(172, 149, 1280, 720);
    add(preview);
}

public void addNotify() {
    preview.addNotify();
    if(thread == null) {
        thread = new Thread(this);
        preview.addKeyListener(this);
        preview.addMouseListener(this);
        thread.start();
    }
}

private void init() {
    image = new BufferedImage(WIDTH, HEIGHT,
            BufferedImage.TYPE_INT_ARGB);
    g = (Graphics2D) image.getGraphics();
    running = true;
}

private long redraw() {

    long t = System.currentTimeMillis();

    if(onTab) {

        if(!FileManager.isSleeping())
            update();

        if(!pause) {
            draw();
            drawToScreen();
        }

    }

    return System.currentTimeMillis() - t;
}

public void run() {

    init();

    while(running) {

        long durationMs = redraw();

        try {
            Thread.sleep(Math.max(0, FPS - durationMs));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

private void update () {
    reupdateImages();
}

private void draw() {
    g.setColor(Color.black);
    g.fillRect(0, 0, WIDTH, HEIGHT);
    for(int i = 0; i < layers.length; i++) {
        if(layers[i] != null) {
            g.drawImage(
                    layers[i].getImage(), 
                    layers[i].getX(), 
                    layers[i].getY(), 
                    layers[i].getWidth(), 
                    layers[i].getHeight(), 
                    null
            );
            g.setColor(Color.red);
            for(int j = 0; j < layers.length; j++) {
                if(layers[j].isSelected()) 
                    g.drawRect(
                            layers[j].getX(),
                            layers[j].getY(),
                            layers[j].getWidth(),
                            layers[j].getHeight()
                    );
            }
        }
    }
}

private void drawToScreen() {
    System.out.println(preview);
    System.out.println(preview.getGraphics());
    Graphics g2 = preview.getGraphics();
    g2.drawImage(image, 0, 0, 
            WIDTH, HEIGHT, 
            null);
    panelImage = image;
    g2.dispose();
}

1 个答案:

答案 0 :(得分:1)

不要覆盖addNotify!

JPanel只有Graphics个实例,并且只有将其添加到父容器中。

Graphics实例是在Component.addNotify()期间构建的,但是您覆盖了它,阻止了它的创建。

也许尝试将super.addNotify()称为快速解决方法。