如何在JFrame中显示BufferedImage?

ano*_*non 15 java swing bufferedimage jframe

我想在同一个JFrame中显示相同图像的变体,例如在JFrame中显示图像,然后用相同图像的灰度替换它.

Ian*_*ill 40

建立在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
Run Code Online (Sandbox Code Playgroud)

  • 我已经很长时间没有使用 swing 了,但我猜如果你有一个小窗口,你就不会调用 `pack()` (2认同)

ldo*_*dog 7

JFrame每次更新图像时都必须重新绘制.

以下是关于该主题的简单谷歌:(我将这些教程用于我所有的Java编码)

Java教程:绘制图像


LiN*_*KeR 5

以防人生苦短,请阅读官方文档,这是一种肮脏的方法,可以多次完成它

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));
}
Run Code Online (Sandbox Code Playgroud)