gpt4 book ai didi

java - 为什么 BufferedImage 输出看起来与 Linux 平台上 JFrame 窗口中的屏幕不同?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:26 25 4
gpt4 key购买 nike

我正在从事一个需要捕获屏幕 GUI(例如 JFrame)图像数据的项目。不知何故,我的应用程序适用于 Windows 和 Mac OS,但对于 Linux,它不会提供与屏幕 GUI 相同的图像输出。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.File;

class jframeExample {

public static BufferedImage getImageData(
Component component) {

BufferedImage image = new BufferedImage(
component.getWidth(),
component.getHeight(),
BufferedImage.TYPE_INT_RGB
);
component.printAll( image.createGraphics() );
return image;
}

public static void main(String[] args){

Runnable r = new Runnable() {
public void run() {
final JFrame f = new JFrame("JFrame Border");
f.setLayout(new BorderLayout());
f.setLocation(500,300);
f.setSize(560, 420);
f.getContentPane().setBackground(Color.BLUE);

JMenuItem screenshot =
new JMenuItem("TakeSnapshot");
screenshot.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae) {
BufferedImage imageOutput = getImageData(f);
try {
// write the image as a PNG
ImageIO.write(
imageOutput,
"png",
new File("CapturedImage.png"));
} catch(Exception e) {
e.printStackTrace();
}
}
} );
JMenu menu = new JMenu("Menu");
menu.add(screenshot);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
f.setJMenuBar(menuBar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);

}
};
SwingUtilities.invokeLater(r);
}
}

以上代码将为 GUI 提供菜单选项,以将其捕获为图像输出。您可以看到屏幕上的 GUI 及其作为附件的图像输出。生成的图像与屏幕上的 GUI 略有不同。查看 JFrame 边框的左/右边缘,它与 contentPane 蓝色重叠。

如何获得与屏幕 GUI 完全相同的图像或调整左/右边框使其不与 contentPane 区域重叠?我使用 LookAndFeel 类尝试了几个选项,但尚未取得任何成功。任何帮助/建议将不胜感激。

On-Screen GUI
CapturedImage

最佳答案

Swing 不会绘制整个框架。框架是操作系统的一个小部件。

尝试使用 Screen Image .

当框架被指定为组件时,它将使用Robot 类来拍摄图像。不然就是会用Swing画。

关于java - 为什么 BufferedImage 输出看起来与 Linux 平台上 JFrame 窗口中的屏幕不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38858943/

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