【发布时间】:2016-08-09 19:29:32
【问题描述】:
我正在开发一个需要捕获屏幕 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 类尝试了几个选项,但还没有取得任何成功。任何帮助/建议将不胜感激。
【问题讨论】:
标签: java linux swing jframe bufferedimage