JPanel上的图像在移动时只会闪烁

时间:2015-03-09 18:34:52

标签: java image

除非我调整窗口大小,否则我绘制的BufferedImage不会显示,即便如此,它只会闪烁:

// Remember, this is a JFrame class
@Override
public void paintComponents(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    super.paint(g2d);
    Graphics p = drawPanel.getGraphics();
    for (int i = 0; i < images.length; i++) {
        BufferedImage im = images[i];
        int ciw = getWidth() / 3;
        int cih = getHeight() / 2;
        int xpos = i % 3;
        int ypos = i / 3;
        int ix = i * ciw * xpos;
        int iy = i * cih * ypos;
        int iw = ciw;
        int ih = cih;
        p.drawImage(im, ix, iy, iw, ih, null);
    }
//  drawPanel.paintComponents(p);
//  drawPanel.repaint();
}

我已完成drawPanel.setDoubleBuffered(true)

如果您想查看整个代码:https://github.com/firestar115/BCMaker

1 个答案:

答案 0 :(得分:3)

此代码包含您不应该做的几件事。

不要覆盖paint()。改为覆盖paintComponent()

不要这样做:

Graphics2D p = (Graphics2D) drawPanel.getGraphics();

相反,只需使用传递给paintComponent()方法的Graphics。

请勿从您自己的绘画代码中致电paint()paintComponent()

相反,只需要在调用repaint()方法时调用paintComponent()即可。如果您希望多次调用它,请使用Timer。请勿在{{1​​}}方法内拨打repaint()

如果您需要更具体的帮助,请提供MCVE