Reputation: 1774
I have successfully done this before but now after running the program numerous times the failure comes at the screenshot is too fast. And it won't take the correct image it takes it as the jframe is fading in. How do I fix this?
Edit : So basically I'm trying to capture the image of the Jpanels inside the JFrame but in the process of doing this by calling it out of an excel macro the image captured turns out to be the one above instead of the image I need.
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;
}
}
}
Upvotes: 0
Views: 2842
Reputation: 6652
It takes time for the operating system to construct and display the frame. Thus the screenshot action is being executed before the frame can be fully displayed.
You can get around it in a couple of ways. The best is probably to use a 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);
}
}
Upvotes: 1