2010-05-18 68 views
2

我正在第一次使用JFrame中的图像,并且出现了一些问题。我成功地在我的JFrame上放置了一个图像,现在我想在2秒后从JFrame中移除我的图像。但2秒后,图像不会消失,除非我调整帧大小或我最小化,然后最大化帧。如果可以,请帮助我。谢谢。删除图像后JFrame不刷新

下面是代码:

 File f = new File("2.jpg"); 

的System.out.println( “图片” + f.getAbsolutePath()); BufferedImage image = ImageIO.read(f); MyBufferedImage img = new MyBufferedImage(image); img.resize(400,300); img.setSize(400,300); img.setLocation(50,50); getContentPane()。add(img);

this.setSize(600,400); this.setLocationRelativeTo(null); this.setVisible(true);

Thread.sleep(2000); System.out.println(“2秒过”);

getContentPane()。remove(img);

这里是MyBufferedImage类:

public class MyBufferedImage extends JComponent{ 
private BufferedImage image; 

private int nPaint; 
private int avgTime; 

private long previousSecondsTime; 

public MyBufferedImage(BufferedImage b) { 
    super(); 

    this.image = b; 

    this.nPaint = 0; 
    this.avgTime = 0; 

    this.previousSecondsTime = System.currentTimeMillis(); 
} 

@Override 
public void paintComponent(Graphics g) { 
    Graphics2D g2D = (Graphics2D) g; 
    g2D.setColor(Color.BLACK); 
    g2D.fillRect(0, 0, this.getWidth(), this.getHeight()); 

    long currentTimeA = System.currentTimeMillis(); 


    //g2D.drawImage(this.image, 320, 0, 0, 240, 0, 0, 640, 480, null); 
    g2D.drawImage(image, 0,0, null); 
    long currentTimeB = System.currentTimeMillis(); 
    this.avgTime += currentTimeB - currentTimeA; 
    this.nPaint++; 

    if (currentTimeB - this.previousSecondsTime > 1000) { 
     System.out.format("Drawn FPS: %d\n", nPaint++); 
     System.out.format("Average time of drawings in the last sec.: %.1f ms\n", (double) this.avgTime/this.nPaint++); 
     this.previousSecondsTime = currentTimeB; 
     this.avgTime = 0; 
     this.nPaint = 0; 
    } 
} 

}

回答

1

只是叫this.repaint()移除图像后一切都会好起来;)

0

你有没有打过电话

的getContentPane()重新验证();

呼叫后删除?

+0

没有重新验证方法,尝试使用的getContentPane()验证()。 或可能(在JFrame上)做this.validateTree(); – 2010-05-18 11:07:10

+0

Doh!此外,他们希望注意添加和删除美国东部时间的东西 – 2010-05-18 11:09:59

0

您可能需要使帧组件无效以强制重绘。

也许你最好的选择是看更新/重绘方法。

0

你应该确保你在Event Dispatch Thread中从你的组件中删除了你的图像。这给一试:

SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
       getContentPane().remove(img); 
     } 
} 

img要么需要在本地范围内的全局或声明final这个工作。如果你不熟悉,请看concepts on Swing Threads

注意:如果内容窗格被视为有效,则Container上的remove调用将调用invalidate()

0

SwingUtilities.updateComponentTreeUI(this);铅球

+0

非常感谢,现在它的工作。它适用于SwingUtilities.updateComponentTreeUI(this),this。重绘或this.update(getGraphics())。祝你今天愉快! – user343908 2010-05-18 14:59:38