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 :/
            Asked
            
        
        
            Active
            
        
            Viewed 447 times
        
    0
            
            
         
    
    
        Paul Samsotha
        
- 205,037
- 37
- 486
- 720
 
    
    
        Coarse
        
- 91
- 1
- 7
- 
                    2Show us your code and what you have tried. Actually you didn't try _everything_. [First hit on google](http://stackoverflow.com/questions/18027833/adding-image-to-jframe). – pzaenger Mar 27 '14 at 15:19
- 
                    Yeah I didn't try literally EVERYTHING, but I DID try that... And like the next 5 pages of Google .-. – Coarse Mar 27 '14 at 19:09
- 
                    _"Because if it's not foolproof, I'm sure to mess it up :/"_ - I like the honesty :-) – Paul Samsotha Mar 28 '14 at 05:20
1 Answers
4
            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();
    }
  }
}
- 
                    HOLY moly!! Thank you SO much! It works! I've spent about 24 hours total looking online for a solution and I f- finally found it!! *Tears of joy* Thanks so much!!!! – Coarse Mar 27 '14 at 18:37
 
    