Reputation: 1
I have this code: `
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Provare extends JFrame {
private JPanel contentPane;
public static int x=100;
public static int y=100;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
x=(int) (100+(x*(Math.random()*3)));
y=(int) (100+(y*(Math.random()*3)));
Provare frame = new Provare();
frame.setVisible(true);
BufferedImage image = new BufferedImage(frame.contentPane.getWidth(),frame.contentPane.getHeight(),BufferedImage.TYPE_INT_RGB );
frame.contentPane.printAll(image.getGraphics());
ImageIO.write(image, "bmp", new File("C:/Users/Resco/Desktop/scarpe/screen.bmp") );
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Provare() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, x, y);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
public void paint(Graphics g){
super.paint(g);
g.drawString("CIAO",(x/2),(x/2));
g.drawLine(50, 50, 100, 100);
}
}
`
What I'd like to get is a screenshot with the text CIAO and a line. What I actually get is a screenshot of an empty element.
Any suggestion? Feel free to post a modify version of my code.
Thanks in advance.
Upvotes: 0
Views: 45
Reputation: 2070
My tip is, that your frame is not ready yet. I would try to call frame.setVisible(true)
in EventQueue.invokeAndWait
and get the screenshot after from the main thread.
Upvotes: 0
Reputation: 22233
You are printing contentPane
contents on the image: contentPane
has nothing to print, it's empty.
You have to use
frame.printAll(image.getGraphics());
Side note: You should not override the paint
method from JFrame
to perform custom painting. Override the paintComponent
method from JPanel
instead.
Upvotes: 2