Java JPanel上的图像仅在移动时闪烁
我有一个我绘制的Java JPanel上的图像仅在移动时闪烁,java,image,Java,Image,我有一个我绘制的buffereImage,除非我调整窗口大小,否则它不会显示,即使如此,它也只会闪烁: // Remember, this is a JFrame class @Override public void paintComponents(Graphics g) { Graphics2D g2d = (Graphics2D) g; super.paint(g2d); Graphics p = drawPanel.getGraphics(); for (
buffereImage
,除非我调整窗口大小,否则它不会显示,即使如此,它也只会闪烁:
// 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();
}
//记住,这是一个JFrame类
@凌驾
公共组件(图形g){
Graphics2D g2d=(Graphics2D)g;
超级油漆(g2d);
Graphics p=drawPanel.getGraphics();
对于(int i=0;i
我已经完成了drawPanel.setDoubleBuffered(true)
如果您想查看整个代码:此代码包含一些您不应该执行的操作 不要覆盖
paint()
。改为覆盖paintComponent()
不要这样做:
Graphics2D p = (Graphics2D) drawPanel.getGraphics();
相反,只需使用传递到paintComponent()方法中的图形即可
不要从自己的绘制代码调用paint()
或paintComponent()
相反,当您希望调用paintComponent()
方法时,只需调用repaint()
。如果您希望它被多次调用,那么使用计时器。也不要从paintComponent()
方法内部调用repaint()
如果您需要更具体的帮助,请提供。制作
buffereImage
以绘制图像。然后,在drawPanel.getGraphics()上绘制BuffereImage
。不要调用repaint()
@覆盖
公共组件(图形g){
//Graphics2D g2d=(Graphics2D)g;
//超级油漆(g2d);
Graphics p=bi.getGraphics();
对于(int i=0;i
您是否尝试了双缓冲?1+,不要从您自己的绘制代码中调用paint()或paintComponent()。相反,只需调用repaint()。
,只是为了澄清一下,您不应该在绘制代码中调用paint()或paintComponent()或repaint()。谢谢@camickr。我已经编辑了我的答案(希望)变得更明显一点。我尝试了一个延迟为1的计时器,但它的延迟非常可怕。另外,JFrame没有paintcomponent()
方法,它有paintComponents()
@moo\u我们所有人都这样做,然后不扩展JFrame,而是扩展JPanel。你必须研究适当的线程(你必须在更新游戏状态时考虑帧间时间),以获得一个非滞后的游戏循环。
@Override
public void paintComponents(Graphics g) {
// Graphics2D g2d = (Graphics2D) g;
// super.paint(g2d);
Graphics p = bi.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.drawImage(bi, 0, 0, null);
// drawPanel.paintComponents(p);
// drawPanel.repaint();
}