如何从jframe捕获图像?(太快了。)

| 我之前已经成功完成了此操作,但现在在运行该程序无数次之后,由于屏幕截图而导致的失败太快了。而且,随着jframe逐渐淡入,它将无法获得正确的图像。如何解决此问题? 编辑:所以基本上我正在尝试捕获JFrame中的Jpanels的图像,但是在此过程中,通过从excel宏调用它,捕获的图像原来是上面的图像,而不是我需要的图像。
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class TimeTableGraphicsRunner extends JFrame
{
    public TimeTableGraphicsRunner()
    {
        getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
    }
    public void load(TimeTablePanel pan)
    {
        pan.setTitle(x.getTitle(TimeTable.titleCount));
        getContentPane().add(pan);
    }
    public void run()throws Exception
    {
        System.out.println(\"Creating image in panel\");
        //setSize(TimeTable.width,TimeTable.height);
        getContentPane().setPreferredSize(new java.awt.Dimension(TimeTable.width,TimeTable.height));
        pack();
        setVisible(true);
        System.out.println(\"Image is in panel\");
        grabScreenShot();
        System.out.println(\"Cleaning up\");
        setVisible(false);
        System.out.println(\"Finished\");
        System.exit(0);
    }
    private void grabScreenShot() throws Exception
    {
        BufferedImage image = (BufferedImage)createImage(getContentPane().getSize().width,getContentPane().getSize().height);
        getContentPane().paint(image.getGraphics());
        try{
            ImageIO.write(image, \"png\", new File(\"C:\\\\Users\\\\\"+TimeTable.user+\"\\\\AppData\\\\TimeLineMacroProgram\\\\TimeLine.png\"));
            System.out.println(\"Image was created\");
        }
        catch (IOException e){
            System.out.println(\"Had trouble writing the image.\");
            throw e;
        }
    }
}
    
已邀请:
        操作系统需要花费一些时间来构造和显示框架。因此,在可以完全显示框架之前正在执行屏幕快照操作。 您可以通过两种方式解决它。最好的方法可能是使用ComponentListener。
public class TimeTableGraphicsRunner extends JFrame implements ComponentListener
{
    public TimeTableGraphicsRunner()
    {
        addComponentListener(this);
        ... snip
    }

    ... snip

    public void componentShown(ComponentEvent e) {
        grabScreenShot();
        System.out.println(\"Cleaning up\");
        setVisible(false);
        System.out.println(\"Finished\");
        System.exit(0);
    }
}
    

要回复问题请先登录注册