java - 如何从jframe捕获图像?(太快)

标签 java image screenshot jframe

我之前已经成功地完成了此操作,但现在在多次运行程序后,失败的原因是屏幕截图太快。当 jframe 淡入时,它不会获取正确的图像。我该如何解决这个问题? Error

编辑:所以基本上我试图捕获 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;
        }
    }
}

最佳答案

操作系统构建和显示框架需要时间。因此,屏幕截图 Action 是在框架完全显示之前执行的。

您可以通过多种方式解决这个问题。最好的可能是使用 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);
    }
}

关于java - 如何从jframe捕获图像?(太快),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6333632/

相关文章:

java - 没有Java的J2ME开发?

Java:外部文本文件的相对路径

android - ImageButton 背景没有改变

c# - Selenium 2(网络驱动程序): Taking a Screenshot returns a black image

android - 屏幕截图代码Android的任何屏幕

python - 是否有与 Java 的 AWT Robot 类等效的 Python?

java - 如何在不使用 Collections.sort() 的情况下按值对 LinkedHashMap 进行排序?

java - Ctrl+Shift+G 在 Eclipse 中不再有效

c# - 使用 WPF 在网格中显示图像

javascript - 如何在 React 中将裁剪参数设置为原始图像?