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();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.