1

I'm trying to make a simple GUI using JAVA no image is shown

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;

public class EmiloLadderSnack {
    public JFrame frame=new JFrame("EmiloLadderSnack");
    public Image img;
    public Graphics g;
    public EmiloLadderSnack()
    {
        frame.setBounds(0, 0, Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        try
        {
            img= ImageIO.read(new File("/media/01CCE00FA6888D80/Achieve/Eclipse/EmiloLadderSnack/src/photo.jpg"));
            g.drawImage(img, 50, 50, null);
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
        }
    }

    public static void main(String args[])
    {
        new EmiloLadderSnack();
    }
}

please help me to show an image in my simple GUI using JAVA I'm using Eclipse

tenorsax
  • 21,123
  • 9
  • 60
  • 107
RofaelEmil
  • 85
  • 4
  • 10
  • Check this link for some sample code:http://www.roseindia.net/java/example/java/swing/DisplayImage.shtml – Hakan Serce Jul 08 '12 at 19:03
  • 1
    [here](http://stackoverflow.com/questions/1064977/setting-background-images-in-jframe) is a similar question whose answer is the best way of doing it IMO – David Kroukamp Jul 08 '12 at 19:07
  • 2
    [Here](http://stackoverflow.com/a/9370871/522444) is another example for an applet and [another one](http://stackoverflow.com/a/9828344/522444) with a JFrame. – Hovercraft Full Of Eels Jul 08 '12 at 19:10
  • 2
    More examples [here](http://stackoverflow.com/a/5129757/230513) and [here](http://stackoverflow.com/a/4054307/230513). – trashgod Jul 08 '12 at 19:17
  • Link to the [basic Swing drawing tutorial](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html), and link to the [advanced Swing drawing tutorial](http://www.oracle.com/technetwork/java/painting-140037.html) – Hovercraft Full Of Eels Jul 08 '12 at 19:19
  • `ImageIO.read(new File(..` That will break at time of deployment, given this is an application/embedded resource. Access it by URL obtained from `getResource(String)`. – Andrew Thompson Jul 10 '12 at 00:40

2 Answers2

4

Hovercraft Full Of Eels is right, as he/she usually is. It really did not look like you tried.

Look at the tutorials, but I do believe when Hovercraft Full Of Eels says the correct way, hover means as follows.

Let me explain what I did below. First I created a new class that extended the JFrame. The JFrame is what is suppose to hold all of the components in a window. Then draw on the JPanel so that all of your drawings are contained in a lightweight container. I set the layout with a new layout I just discovered due to StackOverflow which I am very thankful for. The layout is called the MigLayout and it is a third party resource. You have to download it and import it. Please note that you do not have to have the MigLayout, but it is preferable to use due to its ease of use. After I set the Layout Constraint to fill and docked the JPanel in the center I created a new class which extended the JPanel so that I could change the paint method. The @Override lets you, in a way, re create the method for that extended class. As you can see once draw to that one graphics class then you are all set. There is a lot more you should read up on. Read the comments below your post, they suggest fairly good material.

Anything I get wrong Hovercraft will say below in the comments. So look for that as well.

Hovers corrections:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GraphicExample extends JPanel {
   private static final String IMG_FILE_PATH = "/media/01CCE00FA6888D80/" +
        "Achieve/Eclipse/EmiloLadderSnack/src/photo.jpg";
   private BufferedImage img;

   public GraphicExample(BufferedImage img) {
      this.img = img;
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (img != null) {
         g.drawImage(img, 0, 0, this);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      if (img != null) {
         return new Dimension(img.getWidth(), img.getHeight());
      }
      return super.getPreferredSize();
   }

   private static void createAndShowGui() {
      try {
         BufferedImage img = ImageIO.read(new File(IMG_FILE_PATH));
         JFrame frame = new JFrame("GraphicExample");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().add(new GraphicExample(img));
         frame.pack();
         frame.setLocationRelativeTo(null);
         frame.setVisible(true);

         // the easy way to display an image -- in a JLabel:
         ImageIcon icon = new ImageIcon(img);
         JLabel label = new JLabel(icon);
         JOptionPane.showMessageDialog(frame, label);

      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

My initial recommendations:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;

public class DrawCircle extends JFrame {

    JPanel panel;

    public DrawCircle(String title, int width, int height) {
        this.setTitle(title);
        this.setSize(width, height);
        this.setLocationRelativeTo(null); // Center JFrame
        this.setLayout(new MigLayout("fill"));  // Download external jar
        this.panel = new DrawOval();
        this.add(panel, "dock center");  // Link: http://www.miglayout.com/
        this.setVisible(true);
    }

    public class DrawOval extends JPanel {

            Color color = new Color(1, 1, 1);

        public DrawOval() {

        }

        @Override
        public void paint(Graphics g) {
            g.setColor(color.RED);
            g.fillOval(0, 0, this.getWidth(), this.getHeight());
        }
    }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Zeveso
  • 1,274
  • 3
  • 21
  • 41
  • `"Anything I get wrong Hovercraft will say below in the comments. So look for that as well."`: Yep. I recommend that you draw in the JPanel's `paintComponent` method, not it's `paint` method, else you lose all benefits of Swing double buffering. Not only that, you risk mispainting a component's children and borders. Also I'd call the super's paintComponent method as the first method call. I'd leave MigLayout out of an intro-to Swing painting answer. – Hovercraft Full Of Eels Jul 08 '12 at 19:45
  • @HovercraftFullOfEels What do you mean by "Also I'd call the super's paintComponent method as the first method call."? Do you mean you would switch the order of paintComponent() and DrawOval()? – Zeveso Jul 08 '12 at 19:54
  • I meant that the first method call in `paintComponent(Graphics g)` should be `super.paintComponent(g);`. See edit to your answer above. – Hovercraft Full Of Eels Jul 08 '12 at 20:04
  • @HovercraftFullOfEels Ah, very nice. Thanks... I learned a couple things today which is always nice. – Zeveso Jul 08 '12 at 20:07
1

I can't imagine that this is compiling. There must be a NullPointerException.

When you want to draw something you usually subclass JPanel and do the drawing in the paintComponent() method, like this:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 50, 50, null);
}
11684
  • 7,356
  • 12
  • 48
  • 71