Java 如何在 JFrame 中显示 BufferedImage?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1626735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I display a BufferedImage in a JFrame?
提问by anon
I want to display variations of the same image in the same JFrame, for example display an image in JFrame, then replace it with gray scale of the same image.
我想在同一个 JFrame 中显示同一图像的变化,例如在 JFrame 中显示一个图像,然后用同一图像的灰度替换它。
采纳答案by ldog
You will have to repaint the JFrame
whenever you update the image.
JFrame
每当您更新图像时,您都必须重新绘制。
Here is what a simple google on the topic brings up: (I use those tutorials for all my Java coding)
这是有关该主题的简单谷歌的内容:(我将这些教程用于我所有的 Java 编码)
回答by camickr
I'm not really sure what you question is but if you have a BufferedImage then you simply create an ImageIcon using the image, then you add the icon to a JLabel and add the label to the GUI like any other component.
我不太确定您的问题是什么,但是如果您有一个 BufferedImage,那么您只需使用该图像创建一个 ImageIcon,然后将图标添加到 JLabel 并将标签添加到 GUI 中,就像任何其他组件一样。
If you question is about how to create a gray scale, the I suggest you search the web using those terms as the search keywords, I'm sure you will find examples out there.
如果您的问题是关于如何创建灰度,我建议您使用这些术语作为搜索关键字来搜索网络,我相信您会在那里找到示例。
回答by Ian Will
To build on camickr's solution (for the lazy like me who want quick code to copy/paste) here's a code illustration:
为了建立在 camickr 的解决方案上(对于像我这样想要快速复制/粘贴代码的懒惰者),这里有一个代码说明:
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new JLabel(new ImageIcon(img)));
frame.getContentPane().add(new JLabel(new ImageIcon(img2)));
frame.getContentPane().add(new JLabel(new ImageIcon(img3)));
frame.pack();
frame.setVisible(true);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // if you want the X button to close the app
回答by LiNKeR
Just incase life's to short too read the official docs here's a dirty way to get it done multiple times over
以防万一生命太短暂,请阅读官方文档,这是一种多次完成它的肮脏方法
private static JFrame frame;
private static JLabel label;
public static void display(BufferedImage image){
if(frame==null){
frame=new JFrame();
frame.setTitle("stained_image");
frame.setSize(image.getWidth(), image.getHeight());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
label=new JLabel();
label.setIcon(new ImageIcon(image));
frame.getContentPane().add(label,BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}else label.setIcon(new ImageIcon(image));
}