我想在无头模式下将 JPanel 绘制到 BufferedImage 中(屏幕上根本没有 GUI)。
final JPanel panel = createPanel();
panel.setSize(panel.getPreferredSize());
panel.validate();
// JFrame frame = new JFrame();
// frame.getContentPane().add(panel);
// frame.pack();
// frame.setVisible(true);
final BufferedImage image = new BufferedImage(
panel.getBounds().width,
panel.getBounds().height,
BufferedImage.TYPE_INT_ARGB
);
final Graphics2D gc = image.createGraphics();
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gc.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
try {
panel.paint(gc);
...save the image somewhere...
} finally {
gc.dispose();
}
但是我总是得到空白图像,直到我将面板放入重量级组件并将其显示在屏幕上(请参阅注释代码)。我不想展示它,这个应用程序在服务器上运行。
这是SSCCE:
public class Example {
private static JPanel createPanel() {
final JPanel panel = new JPanel(new GridBagLayout());
final JLabel label = new JLabel("Yeah, it's working!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.PLAIN, 12));
final GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1;
constraints.weightx = 1;
panel.add(label, constraints);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JPanel panel = createPanel();
panel.setSize(panel.getPreferredSize());
panel.validate();
// JFrame frame = new JFrame();
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.getContentPane().add(panel);
// frame.pack();
// frame.setVisible(true);
final BufferedImage image = new BufferedImage(
panel.getBounds().width,
panel.getBounds().height,
BufferedImage.TYPE_INT_ARGB
);
final Graphics2D gc = image.createGraphics();
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gc.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
try {
panel.paint(gc);
ImageIO.write(image, "png", new File("image.png"));
} catch (IOException e) {
e.printStackTrace();
} finally {
gc.dispose();
}
}
});
}
}