如何在JFrame中显示图像 [英] How to show image in JFrame

查看:101
本文介绍了如何在JFrame中显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这很可能被标记为重复的问题,但是请先听我说.我在Internet上四处查看,并尝试了各种方法来在 JFrame 中显示图像,但对我而言没有任何效果.有没有简单,万无一失的工具!在 JFrame 中显示图像的方法?因为如果它不是万无一失的,我一定会把它弄乱了:/

Okay, this is likely to be flagged as a repeated question, but please hear me out first. I have looked all over the internet and have tried various ways to show an image in a JFrame, but nothing has worked for me. Is there any simple, foolproof! way to show an image in JFrame? Because if it's not foolproof, I'm sure to mess it up :/

推荐答案

您可以尝试一下,我已经评论了我所做的事情以及在何处尝试使其易于理解,并包括了有关从

You can try this out, I have commented what I have done and where to try and make it understandable and included a bit about resizing from this post. See how you get on :)

public class SO2 {
  public static void main(String[] args) {
    try {
        //Step 1, read in image using javax.ImageIO
        BufferedImage img = ImageIO.read(new File("D:/Users/user/Desktop/Tree.jpeg"));

        //Optional, if you want to resize image this is an effective way of doing it
        Image scaled = img.getScaledInstance(200, 200, Image.SCALE_SMOOTH); 

        //Step 2 create frame
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Step 3 add image to Frame
        frame.add(new JLabel(new ImageIcon(scaled)));

        //Step 4 Pack frame which sizes it around it's contents, then Show
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

这篇关于如何在JFrame中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆