[英]How to show image in 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. 我已经遍及整个Internet,并尝试了各种方法来在
JFrame
显示图像,但是没有任何效果对我JFrame
。 Is there any simple, foolproof! 有没有简单,简单的方法! way to show an image in
JFrame
? 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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.