Reputation: 385
I managed to draw GUI components on an image. However, it only can be done by having a JFrame
set to be visible. The JPanel.setVisible()
and validate()
don't have any effect. It would draw an empty image if the JFrame
is commented out.
It is not neat when I want some function to do off-screen GUI painting, then pop a JFrame
out or the server running such code don't have a screen or graphic card.
Please help, thanks very much.
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Snippet {
public static void main(String[] args) {
JButton test = new JButton("Test Button center");
JButton test2 = new JButton("Test Button2 south");
JButton test3 = new JButton("Test Button3 at east");
BorderLayout bl = new BorderLayout();
JPanel jp = new JPanel(bl, false);
jp.add(test2,BorderLayout.SOUTH);
jp.add(test, BorderLayout.CENTER);
jp.add(test3, BorderLayout.EAST);
// jp.validate();
// jp.setVisible(true);
// jp.show();
JFrame jf = new JFrame();
jf.getContentPane().add(jp, BorderLayout.CENTER);
jf.pack();
jf.setVisible(true);
//jp.setBounds(10, 10, 400, 400);
BufferedImage b = new BufferedImage(jf.getWidth(), jf.getHeight(), BufferedImage.TYPE_INT_ARGB);
jp.paintAll(b.createGraphics());
File output = new File("f:/screenie.png");
try
{
ImageIO.write(b, "png", output);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Upvotes: 1
Views: 1211
Reputation: 324118
i managed drawing GUI components on image, however, it only can be done by having a Jframe set to be visible,
Components need to have a size before they can be painted. By default the size of a component is (0, 0) so there is nothing to paint. When you invoke pack() or setVisible(...) - which invokes pack() for you - the size of each component is then determined.
Check out Screen Image which can be used to create an image of any component and will set the size for you before creating the image.
Upvotes: 1