我第一次使用JFrame中的图像,我遇到了一些问题。我成功地将图像放在我的JFrame上,现在我希望在2秒后从JFrame中删除我的图像。但是2秒后,图像不会消失,除非我调整帧的大小或最小化,然后最大化帧。如果可以,请帮助我。感谢。
以下是代码:
File f = new File("2.jpg");
System.out.println(“Picture”+ 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()添加(IMG);
this.setSize(600,400); this.setLocationRelativeTo(NULL); this.setVisible(真);
的Thread.sleep(2000); System.out.println(“2秒以上”);
的getContentPane()除去(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;
}
}
}
答案 0 :(得分:1)
删除图片后只需致电this.repaint()
,一切顺利;)
答案 1 :(得分:0)
您是否尝试过调用
getContentPane()。revalidate();
调用后删除?
答案 2 :(得分:0)
您可能需要使框架组件无效,从而强制重绘。
可能你最好的办法是查看更新/重绘方法。
答案 3 :(得分:0)
您应确保在Event Dispatch Thread中从组件中删除图像。试一试:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getContentPane().remove(img);
}
}
您的img
将需要在本地范围内成为全局或声明final
才能生效。如果您还不熟悉,请查看concepts on Swing Threads。
注意:如果内容窗格被视为有效,则remove
上的Container
电话会调用invalidate()
。
答案 4 :(得分:0)
提供
SwingUtilities.updateComponentTreeUI(this);
一个镜头