gpt4 book ai didi

java - headless 画

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:28:31 34 4
gpt4 key购买 nike

我想以 headless 模式(屏幕上根本没有 GUI)将 JPanel 绘制到 BufferedImage 中。

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();
}
}
});
}
}

最佳答案

在实现组件之前,组件的大小为零,因此绘制方法不起作用。

查看 Screen Image .它将通过在面板上调用 doLayout() 来为您处理这个问题,以确保所有组件都具有有效尺寸。

关于java - headless 画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026803/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com