How to show image in JFrame

别等时光非礼了梦想. 提交于 2021-01-29 07:19:23

问题


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 :/


回答1:


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();
    }
  }
}


来源:https://stackoverflow.com/questions/22691820/how-to-show-image-in-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!