Image in JPanel

I am trying, as so many others, to print an image to a frame. i am using a panel to do so. I just don't get any images to show up... Thanx for your help!!!
here my code...
public class MyFrame exends JFrame {
private void initComponents() {
JPanel welcomePanel = new JPanel();
BoxLayout box = new BoxLayout(welcomePanel, BoxLayout.Y_AXIS);
welcomePanel.setLayout(box);
JPanel intro2 = new JPanel();
BoxLayout box2 = new BoxLayout(intro2,BoxLayout.X_AXIS);
intro2.setLayout(box2);
ImagePanel leftImg = new ImagePanel("cooked_turkey_walking.gif");
ImagePanel rightImg = new ImagePanel("cup_anim_e0.gif");
intro2.add(leftImg);
intro2.add(rightImg);
welcomePanel.add(intro2);
//add the general panel to the frane
getContentPane().add(welcomePanel);
class ImagePanel extends JPanel {
private Toolkit b = Toolkit.getDefaultToolkit();
private Image img;
public ImagePanel(String imageName)
super();
img = b.getImage(imageName);
public void paint(Graphics g)
g.drawImage(img,0,0,this);
super.paint(g);
}

Hello,
well, I did it somewhat differently, but I can see ma picture.
//  *** Picture-Panel ***
    Icon icon =  new ImageIcon("./images/OmBlue.jpg");
    JLabel imgLabel = new JLabel(icon);
//  imgLabel.setBounds(0,0,200,200);
    Insets insets= getInsets();
    int b= this.getWidth();//-insets.left-insets.right;
    int h= this.getHeight();//-insets.top-insets.bottom;
    imgLabel.setBounds(0,0,b,h);
    picturePanel.add(imgLabel);Hth
J�rg

Similar Messages

  • Background image  for JPanel using UI Properties

    Is there any way to add background image for JPanel using UI Properties,
    code is
    if (property.equals("img")) {
    System.out.println("call image file in css"+comp);
    //set the background color for Jpanel
    comp.setBackground(Color.decode("#db7093"));
    here the comp is JPanel and we are setting the background color,
    Is there any way to put the Background image for the JPanel ????

    KrishnaveniB wrote:
    Is there any way to put the Background image for the JPanel ????Override the paintComponent(...) method of JPanel.
    e.g.
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    public class ImagePanel {
        public void createAndShowUI() {
            try {
                JFrame frame = new JFrame("Background Image Demo");
                final Image image = ImageIO.read(new File("/home/oje/Desktop/icons/yannix.gif"));
                JPanel panel = new JPanel() {
                    protected void paintComponent(Graphics g) {
                        g.drawImage(image, 0, 0, null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(new Dimension(400, 400));
                frame.setContentPane(panel);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException ex) {
                ex.printStackTrace();
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new ImagePanel().createAndShowUI();
    }

  • Displyaing image in JPanel

    I am using below code to display image in jpanel.
    It is not displaying image. Please help me.
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Toolkit;
    import java.awt.Image;
    public class project extends JPanel {
         public void init()
              JFrame mFrame = new JFrame("Documentum Login");
              mFrame.setSize(350,200);
    //mFrame.setResizable(false);
    Dimension dim = getToolkit().getScreenSize();
    mFrame.setLocation((dim.width/2) - (mFrame.getWidth()/2),(dim.height/2) - (mFrame.getHeight()/2));
              //JPanel hpan = new JPanel();
    //hpan.setLayout(new BoxLayout(hpan,BoxLayout.Y_AXIS));
    //hpan.setBorder(new TitledBorder (new LineBorder (Color.blue, 1)));
              //Image img = Toolkit.getDefaultToolkit().getImage("D:/Temp/test.jpg");
              ImageIcon icon = new ImageIcon("D:\\Temp\\test.jpg");
              JLabel imageLabel = new JLabel(icon);
              JScrollPane scrollPane = new JScrollPane (JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scrollPane.getViewport().add(imageLabel);
              JPanel panel = new JPanel();
              panel.setLayout(new BorderLayout());
              panel.add(scrollPane,BorderLayout.CENTER);
              mFrame.getContentPane().add(panel);
    mFrame.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e) {System.exit(0); }
    mFrame.setVisible(true);
         public static void main(String args[])
              project pr = new project();
              pr.init();          
    }

    Don't add() to a JViewport, setView() instead.

  • Display a transparent image in JPanel

    i just start using Java Graphics Programming fews month ago. there's some problem i facing recently. i doing a simple gif file viewer. first i get the file using the Toolkit and put it in a Image object and use the Gif Decoder to decoded each frame of the Gif File to BufferedImage object and display each of the frame in a JPanel inside a JFrame.My porblem is :-
    How to display a transparent image in JPanel? my image source in BufferedImage and how to i know the image is transparent or not?

    I simply use ImageIcon object to display the image (*.gif,*.jpg)
    JLabel l=new JLabel(new ImageIcon("file path"));
    add the label to a panel or frame or dialog
    this object no need to use the ImageBuffered Object
    It can display any animate gif whether the background is transparent or not.

  • Having trouble displaying image in JPanel

    I want to display an image in jpanel making it to scale to the size of the panel.
    And later i should be able to draw on that image , i am really new to all this , but i have to finish it soon.
    This is the code i am compiling and getting error
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class LocaterClient extends JFrame
         JPanel panel;
         public LocaterClient()
              super("LocaterClient");
              panel = new JPanel();
              panel.setSize(374,378);
              panel.setOpaque(false);
              panel.setVisible(true);
         getContentPane().add(panel);
         /*JFrame f = new JFrame();
         f.setSize(374,378);
         f.getContentPane().add(panel);*/
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              ImageIcon img = new ImageIcon("World_MER.jpg");
              ImageIcon fillImage = new ImageIcon(img.getImage().getScaledInstance
    (getWidth(), getHeight(),Image.SCALE_REPLICATE));
              g.drawImage(fillImage.getImage(), 0,0, this);
         public static void main(String args[])
              LocaterClient lc = new LocaterClient();
              lc.setDefaultCloseOperation( EXIT_ON_CLOSE );
              lc.pack();
              lc.setVisible(true);
    This is the error i am getting
    LocaterClient.java:24: cannot resolve symbol
    symbol : method paintComponent (java.awt.Graphics)
    location: class javax.swing.JFrame
    super.paintComponent(g);
    ^
    1 error
    If i remove super.paintComponent(g); line it compiles and runs but i get a tiny panel without the image.
    PLease help me , i am not evn sure is this is the procedure should i follow , because i should be able to draw on that image later on .
    Please provide me with some sample code.

    import javax.swing.*;
    import java.awt.*;
    public class ImagePainter extends JPanel{
      private Image img;
      public ImagePainter(){
        img = Toolkit.getDefaultToolkit().getImage("MyImage.gif");
      public void paintComponent(Graphics g){
        g.drawImage(img,0,0,getSize().width,getSize().height);
      public static void main(String[]args){
        JFrame frame = new JFrame();
        frame.getContentPane.add(new ImagePainter());
        frame.setSize(500,500);
        frame.show();

  • Adding Image to JPanel?

    Hi all,
    I am new to Swing..
    How to add the "Image" to JPanel.
    if anyone knows please help me..
    Thanks

    Here's a long reply involving several classes, some obtained directly from Sun for reuse. These allow you to fill an image in a panel as the background to your frame. You can add components on top of this background image. If this isn't what you wanted, excuse my misunderstanding:
    First, you need a panel for your frame:
    <code>
    public class FramePanel extends JPanel
    * Initialized by the (first call to the) constructor. This
    * Fill is used to paint the entire panel.
    private static TiledFill tiledFill = null;
    /*Constructors */
    public FramePanel()
    super();
    setOpaque(true);
    * Create a TiledFill object to draw the
    * background from preferences properties file
    public void getBackgroundImage()
    setForeground(Color.BLACK);
    setBackground(Color.WHITE);
    if (tiledFill == null)
    try
    FileImageInputStream file = new FileImageInputStream(*your image's file location*);
    BufferedImage image = ImageIO.read(file);
    ImageFill fill = new ImageFill(image);
    tiledFill = new TiledFill(fill, image.getWidth(), image.getHeight());
    catch (IOException e)
    e.printStackTrace();
    JOptionPane pane = new JOptionPane("Could not retrieve image in FramePanel");
    pane.setVisible(true);
    * Paint the area within <code>g.getClipBounds()</code>
    * making sure that the new tiles are aligned with a tileWidth
    * by tileHeight grid whose origin is at 0,0.
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    getBackgroundImage();
    /* To ensure that the tiles we paint are aligned with
    * a tileWidth X tileHeight grid whose origin is 0,0 we
    * enlarge the clipBounds rectangle so that its origin
    * is aligned with the origin of a tile and its size
    * is a multiple of the tile size.
    Rectangle clip = g.getClipBounds();
    int tw = tiledFill.getTileWidth();
    int th = tiledFill.getTileHeight();
    int x = (clip.x / tw) * tw;
    int y = (clip.y / th) * th;
    int w = (((clip.x + clip.width + tw - 1) / tw) * tw) - x;
    int h = (((clip.y + clip.height + th - 1) / th) * th) - y;
    Graphics gFill = g.create();
    tiledFill.paintFill(this, gFill, new Rectangle(x, y, w, h));
    gFill.dispose();
    </code>
    Now you need the fill and tiled fill classes size the image.
    <code>
    import java.awt.*;
    public class Fill
    public void paintFill(Component c, Graphics g, Rectangle r)
    g.setColor(c.getBackground());
    g.fillRect(r.x, r.y, r.width, r.height);
    public void paintFill(Container c, Graphics g)
    Insets insets = c.getInsets();
    int x = insets.left;
    int y = insets.top;
    int w = c.getWidth() - (insets.left + insets.right);
    int h = c.getHeight() - (insets.top + insets.bottom);
    paintFill(c, g, new Rectangle(x, y, w, h));
    public void paintFill(Component c, Graphics g, int x, int y, int w, int h)
    paintFill(c, g, new Rectangle(x, y, w, h));
    </code>
    <code>
    import java.awt.*;
    import java.awt.image.*;
    * Displays a single <code>BufferedImage</code>, scaled to fit the
    * <code>paintFill</code> rectangle.
    * <pre>
    * BufferedImage image = ImageIO.read(new File("background.jpg"));
    * final ImageFill imageFill = new ImageFill(image);
    * JPanel p = new JPanel() {
    * public c void paintComponent(Graphics g) {
    *     imageFill.paintFill(this, g);
    * </pre>
    * Note that animated gifs aren't supported as there's no image observer.
    public class ImageFill extends Fill
    private final static int IMAGE_CACHE_SIZE = 8;
    private BufferedImage image;
    private BufferedImage[] imageCache = new BufferedImage[IMAGE_CACHE_SIZE];
    private int imageCacheIndex = 0;
    * Creates an <code>ImageFill</code> that draws <i>image</i>
    * scaled to fit the <code>paintFill</code> rectangle
    * parameters.
    * @see #getImage
    * @see #paintFill
    public ImageFill(BufferedImage image)
    this.image = image;
    * Creates an "empty" ImageFill. Before the ImageFill can be
    * drawn with the <code>paintFill</code> method, the
    * <code>image</code> property must be set.
    * @see #setImage
    * @see #paintFill
    public ImageFill()
    this.image = null;
    * Returns the image that the <code>paintFill</code> method draws.
    * @return the value of the <code>image</code> property
    * @see #setImage
    * @see #paintFill
    public BufferedImage getImage()
    return image;
    * Set the image that the <code>paintFill</code> method draws.
    * @param image the new value of the <code>image</code> property
    * @see #getImage
    * @see #paintFill
    public void setImage(BufferedImage image)
    this.image = image;
    for (int i = 0; i < imageCache.length; i++)
    imageCache[i] = null;
    * Returns the actual width of the <code>BufferedImage</code>
    * rendered by the <code>paintFill</code> method. If the image
    * property hasn't been set, -1 is returned.
    * @return the value of <code>getImage().getWidth()</code> or -1 if
    * getImage() returns null
    * @see #getHeight
    * @see #setImage
    public int getWidth()
    BufferedImage image = getImage();
    return (image == null) ? -1 : image.getWidth();
    * Returns the actual height of the <code>BufferedImage</code>
    * rendered by the <code>paintFill</code> method. If the image
    * property hasn't been set, -1 is returned.
    * @return the value of <code>getImage().getHeight()</code> or -1 if
    * getImage() returns null
    * @see #getWidth
    * @see #setImage
    public int getHeight()
    BufferedImage image = getImage();
    return (image == null) ? -1 : image.getHeight();
    * Create a copy of image scaled to width,height w,h and
    * add it to the null element of the imageCache array. If
    * the imageCache array is full, then we replace the "least
    * recently used element", at imageCacheIndex.
    private BufferedImage createScaledImage(Component c, int w, int h)
    GraphicsConfiguration gc = c.getGraphicsConfiguration();
    BufferedImage newImage = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
    boolean cacheOverflow = true;
    for (int i = 0; i < imageCache.length; i++)
    Image image = imageCache;
    if (image == null)
    imageCache[i] = newImage;
    cacheOverflow = false;
    break;
    if (cacheOverflow)
    imageCache[imageCacheIndex] = newImage;
    imageCacheIndex = (imageCacheIndex + 1) % imageCache.length;
    Graphics g = newImage.getGraphics();
    int width = image.getWidth();
    int height = image.getHeight();
    g.drawImage(image, 0, 0, w, h, 0, 0, width, height, null);
    g.dispose();
    return newImage;
    * Returns either the image itself or a cached scaled copy.
    private BufferedImage getFillImage(Component c, int w, int h)
    if ((w == getWidth()) && (h == getHeight()))
    return image;
    for (int i = 0; i < imageCache.length; i++)
    BufferedImage cimage = imageCache[i];
    if (cimage == null)
    break;
    if ((cimage.getWidth(c) == w) && (cimage.getHeight(c) == h))
    return cimage;
    return createScaledImage(c, w, h);
    * Draw the image at <i>r.x,r.y</i>, scaled to <i>r.width</i>
    * and <i>r.height</i>.
    public void paintFill(Component c, Graphics g, Rectangle r)
    if ((r.width > 0) && (r.height > 0))
    BufferedImage fillImage = getFillImage(c, r.width, r.height);
    g.drawImage(fillImage, r.x, r.y, c);
    </code>
    Now it's just a simple matter of creating a frame and making the frame panel the frame's content pane:
    <code>
    import java.awt.BorderLayout;
    import java.awt.HeadlessException;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    public class ImageFrame extends JFrame
    private FramePanel framePanel;
    //start of constructors
    public ImageFrame() throws HeadlessException
    super();
    init();
    public ImageFrame(String title) throws HeadlessException
    super(title);
    init();
    // end of constructors
    void init()
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch (Exception e)
    System.out.println ("Unknown Look and Feel");
         framePanel = new FramePanel();
         this.getContentPane().add(framePanel, BorderLayout.CENTER);
         this.setContentPane(framePanel);
         ((JPanel)this.getContentPane()).setOpaque(false);
    </code>

  • Displaying DICOM images in JPanel

    Can anyone please tell me how to display DICOM images using JPanel? I can use JPanel to display ordinary images but it does not seem to work using DICOM images. Can anyone please help me out? I've spent hours and hours trying to solve this problem. Thank you in advance.

    Can anyone please tell me how to display DICOM images
    using JPanel? I can use JPanel to display ordinary
    images but it does not seem to work using DICOM
    images. Can anyone please help me out? I've spent
    hours and hours trying to solve this problem. Thank
    you in advance.The JPanel is only able to display JPEG and GIF images, you will need to decode the DICOM image first and convert to JPEG or GIF format, there are some source codes available on the net. Also check this link out
    http://www.dclunie.com/medical-image-faq/html/part8.html

  • Putting an Image in JPanel

    I am trying to put an image in JPanel. Using something other than ImageIcon. When I run the program only a white screen appears.
    package game;
    import gui.FullScreenDisplay;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.Runnable;
    import java.lang.Thread;
    public class Runner implements Runnable
         private static final long serialVersionUID = 1L;
         private FullScreenDisplay display;
         public static void main(String args[])
              Thread t = new Thread(new Runner());
              t.start();
         public Runner()
              makeGui();
         private void makeGui()
              display = new FullScreenDisplay(this);
         public void run()
              try {
                   Thread.sleep(1000);
              } catch (InterruptedException e) {/*Nothing to do*/}
              run();
         public void quit()
              System.exit(0);
    package gui;
    import game.Runner;
    import java.awt.GraphicsEnvironment;
    import java.awt.event.KeyEvent;
    import javax.swing.KeyStroke;
    import javax.swing.AbstractAction;
    import java.awt.event.ActionEvent;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.imageio.ImageIO;
    import java.io.File;
    import java.io.IOException;
    public class FullScreenDisplay extends JFrame {
         private static final long serialVersionUID = 1L;
         private Runner master;
         private JPanel mainPanel;
         private Image tempImage;
         public FullScreenDisplay(Runner master)
              super();
              //Remove this eventually.
              try {
                   tempImage = ImageIO.read(new File("test_image.jpg"));
              } catch (IOException e) {
                   System.out.println("image get error");
                   e.printStackTrace();
              this.master = master;
              makeFrame();
              makePanel();
              makeKeyBindings();
              //setFullScreen(chooseBufferStrategy());
              setFullScreen();
              requestFocus();
              setVisible(true);
              //Remove this eventually.
              Graphics g = tempImage.getGraphics();
              mainPanel.paint(g);
              this.update(g);
         private void makeFrame()
              setUndecorated(true);
              setResizable(false);
              setFocusable(true);
         private void makePanel()
              mainPanel = new JPanel(){
                   public void paintComponent(Graphics g) {
                        if(tempImage == null){
                             System.out.println("Balls");
                        g.drawRect(10, 10, 10, 10);
                        g.drawImage(tempImage,0,0,null);
                        super.paintComponent(g);
                        System.out.println("Did it work");
              add(mainPanel);
         private void makeKeyBindings()
              mainPanel.setFocusable(true);
              //Key bindings... don't like using a string to index, find out if there's a better way.
              mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "exit");
              mainPanel.getActionMap().put("exit", new AbstractAction(){
                   public void actionPerformed(ActionEvent e)
                        master.quit();
         /*private void chooseBufferSrategy()
         private void setFullScreen()
              GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
    }

    super.paintComponent(g);should be the first line in paintComponent()
    also, you don't really need the keyBindings to quit,
    just set the default close to exit and Alt-F4 will close/quit

  • How can I move some image on JPanel ?

    How can I move some image on JPanel ?
    I want to move it with my arrow keys.
    Plees, give me example code

    1) Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]Using Layout Managers. You would need to use Absolute Positioning so you can control the position of the image
    2) Add the image to a JLabel and the label to the panel
    3) Read the tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings. Then you just assign an Action to each of the arrow keys and use setLocation(...) to move the label.

  • Copying image to jpanel

    when i copy an image to jpanel using jlabel i.e
    jlabel lab = new jlabel(new Iconimage("xyz.jpg"));
    i cannot listen to any keys being pressed on the label when i want to copy the image onto a clip board( cntrl C). Is there any method of listening to keys being pressed on jlabel or a method to display the image on jpanel which listens to keys.

    can give code to draw image on Panel.
    icon = new ImageIcon("backUp.gif");
    JPanel panel = new JPanel()
         protected void paintComponent(Graphics g)
              g.drawImage(icon.getImage(), 0, 0, null);
              super.paintComponent(g);
    panel.setOpaque( false );

  • Display image in JPanel without saving any file to disk

    Hi,
    I am fetching images from database. I am saving this image, display in JPanel and delete it. But this is not actually I want.
    I wish to fetch this image as stream , store in memory and display in JPanel without saving any fiel in disk.
    I wonder if it is Possible or any used implementation that I can use in my project. Any idea or experienced knowledge is enough.
    Thanks

    In what format is the image coming to you from the database? If it's an InputStream subclass, just use javax.imageio.ImageIO:
    InputStream in = getImageInputStream();
    BufferedImage image = null;
    try {
       image = ImageIO.read(in);
    } finally {
       in.close();
    // ... Display image in your JPanel as you have beenIf you receive the image as an array of bytes, use the same method as above, but with a ByteArrayInputStream:
    byte[] imageData = getImageData();
    ByteArrayInputStream in = new ByteArrayInputStream(imageData);
    BufferedImage image = null;
    try {
       image = ImageIO.read(in);
    } finally {
       in.close();
    // ... Display image in your JPanel as you have been

  • Background Image in JPanel.

    Hi, I am trying to set a background image to my JPanel. So far everything ok. However When I add labels to this panel as well the image is displayed but the label is not! I tried to make a search on google, and I found some links pointing to this forum, however none of them (which) I have seen show how to display a backgroun image and a label on top.
    What I tried to to is override the paint method of the JPanel. Here I did the following code:
    public void paint(Graphics g){
       Image i = this.myImage // Were myImage is of type Image with a loaded image in.
       g = super.getGraphics();
       g.drawImage(i, 0, 0, this);
       super.paint(g);
    }However this code brings the label and the image always blinking. I can imagine the reason for this is that the paint method is called all the time, and thus the image and the label are being painted all the time and so there is the blinking effect.
    Does anyone know how I can set a background image to my JPanel in an efficient way?

    No Gosling? I just retried it and it works for me.
    Maybe you're having trouble with the image URL.
    Try it with a local image.

  • How to put images on JPanel one at a time?

    Hi, guys. I am trying to put 7 images to a panel one by one,each takes one second so that users can see the process each images being shown on the panel.
    But the fact is the system freeze for 7 seconds and then display them all once. Altho the "one image has been dealt" showsin the console every one second.
    Thank you
    Here is the code :
    for (int i=0;i<7 ;i++ )
                   try
                   thisTile[i] = new tiles(BBV.string,"BlackBack",100,100);
                   thisTile.setBounds(x1,y1,27,49);               
                   JP1.add(thisTile[i]);                              
                   y1=y1+54;
                   System.out.println("one image has been dealt");
                   Thread.sleep(1000);
                   catch (InterruptedException e)
                        System.out.println("this should not be printed");

    for example, I want to print "all 7 images has been dealt" after the images have been put on the JPanel, by using swing timer it prints the "all 7 images has been dealt" during/before the images being put. Here is the code example(thisTile is a array of 7 images):
    public void showImages()
    t = new javax.swing.Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
                   thisTile[j] = new tiles(BBV.string,"BlackBack",100,100);
                   thisTile[j].setBounds(x1,y1,27,49);               
                   JP1.add(thisTile[j]);
                   JP1.validate();
                   JP1.repaint();
                   y1=y1+54;
                   j++;
                   if (j==7)
                        t.stop();
              //AI1 gets his tiles
              for (int i=0;i<7 ;i++ )
                   t.start();               
              System.out.println("all images has been dealt");
              }

  • How to display image at jpanel in application GUI

    i wana load an image from given location to my GUI when application starts.
    according to my perception this code should load image but its not working.
    Will any body kindly help me and point out the "reasons" for not working following piece of code from my application.
    public class MainFrame extends JFrame
    JPanel jPanel1 = new JPanel();
    JPanel jPanel2 = new JPanel();
    JButton jButton1 = new JButton();
    JButton jButton2 = new JButton();
    Image image = Toolkit.getDefaultToolkit().createImage("c:\\form-3.jpg");
    javax.swing.JScrollBar jScrollBar1 = new JScrollBar();
    BorderLayout borderLayout1 = new BorderLayout();
    public MainFrame()
    try
    jbInit();
    } catch (Exception ex)
    ex.printStackTrace();
    public static void main(String[] args)
    MainFrame mainFrame = new MainFrame();
    private void jbInit() throws Exception
         //jbInit() defined here
    public void paintComponent(Graphics g)
    // jPanel1.getGraphics().drawImage(image,0,0,jPanel1);
    Graphics2D g2D = (Graphics2D) g;
    BufferedImage bi = (BufferedImage) createImage(getWidth(),getHeight());
    bi.createGraphics().drawImage(image, 0,0, jPanel1);
    // g.drawImage(image,0,0,jPanel1);
    public void jButton2_mouseClicked(MouseEvent e)
         public void jButton1_mouseClicked(MouseEvent e)
    this.dispose();
    System.exit( 0 );
    /////////////////////////////////////////////////////////////////////////////

    this works OK
    (stripped of everything unrelated to your question)
    import javax.swing.*;
    import java.awt.*;
    class MainFrame extends JFrame
      Image image = Toolkit.getDefaultToolkit().createImage("test.gif");
      public static void main(String[] args)
        MainFrame mainFrame = new MainFrame();
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(200,200);
        mainFrame.setVisible(true);
      public void paint(Graphics g)//<-----heavyweight component
        super.paint(g);
        g.drawImage(image,50,50,this);
    }

  • Background image for JPanel

    I was to come here and "search" for examples on this but i havnt found any so im jsut going to post it:
    How do i set an image to be the background of a JPanel? setBackground(image); doesnt work... i was toal something about paintComponent() but i tried it with that too and it didnt work... anyhelp would be greatly appreciated

    Ive tried many of the things that search suggested but none of them pertained enough to what i am doing for it to work. Here is my code:package gameFunctions;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class loginScreen extends JFrame implements ActionListener
         JTextField USERNAME, Username, PASSWORD, Password; // yeah i know, bad practice but there is some logic to the names relative to capitalization
         String username, password;
         JButton LOGIN;
         Dimension res = Toolkit.getDefaultToolkit().getScreenSize();
         ImageIcon background = new ImageIcon("C:\\FileTesting\\testImage.jpg");;
         JPanel pane;
    public static void main(String[] args)
              loginScreen frame = new loginScreen();
              frame.setVisible(true);
    public loginScreen()
              Container c = getContentPane();
              setSize(400, 300);
              setLocation((int)res.getWidth()/2-getWidth()/2, (int)res.getHeight()/2-getHeight()/2);
              setResizable(false);
              setLayout(null);
              pane = new JPanel();
              pane.setSize(getWidth(), getHeight());
              pane.setLayout(null);
              c.add(pane);
              USERNAME = new JTextField("Username:");
              USERNAME.setSize(68,25);
              USERNAME.setLocation(getWidth()/2-USERNAME.getWidth()/2-80, getHeight()/2-USERNAME.getHeight()/2-50);
              USERNAME.setEditable(false);
              pane.add(USERNAME);
              PASSWORD = new JTextField("Password:");
              PASSWORD.setSize(68,25);
              PASSWORD.setLocation(USERNAME.getX(), USERNAME.getY()+30);
              PASSWORD.setEditable(false);
              pane.add(PASSWORD);
              Username = new JTextField();
              Username.setSize(150,25);
              Username.setLocation(USERNAME.getX()+USERNAME.getWidth()+5, USERNAME.getY());
              Username.setEditable(true);
              pane.add(Username);
              Password = new JTextField();
              Password.setSize(150,25);
              Password.setLocation(Username.getX(), Username.getY()+30);
              Password.setEditable(false); // because im not working with PW's yet
              pane.add(Password);
              LOGIN = new JButton("LOGIN");
              LOGIN.setSize(80,30);
              LOGIN.setLocation(getWidth()/2-LOGIN.getWidth()/2, PASSWORD.getY()+30);
              pane.add(LOGIN);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
    public void actionPerformed(ActionEvent event)
    }i want "pane" to be the image of "background" imageIcon is the only thing that works like this because i dont know how to use straight up "Image". everything works if i set the ImageIcon "background" to be the background of JButton "LOGIN"
    any help would be greatly appreciated

  • Problem displaying image in jpanel

    Hi,I have posted this on the applet board, but I think its also a general programming problem, so apologies if it isn't relevant to this board, just say so and I'll remove it!
    I've got an applet that receives a variable from a PHP page as a parameter. The variable is "map1.png" the map this variable refers to sits in the same folder as the applet.
    I want to use this variable along with getDocumentBase() to create a URL which will then be used to display an image within a jPanel called mapPane.
    the code I currently have is:
    // get image url
    String mapURL = getParameter("mapURL");
    //set variable for image
    Image map_png;
    // set media tracker
    MediaTracker mt;
    //initialise media tracker     
    mt = new MediaTracker(this);
    map_png = getImage(getDocumentBase(),mapURL);
    // tell the MediaTracker to kep an eye on this image, and give it ID 1;
    mt.addImage(map_png,1);
    // now tell the mediaTracker to stop the applet execution
    // until the images are fully loaded.
    try
    mt.waitForAll();
    catch (InterruptedException e) {}
    // draw image onto mapPane
    mapPane.getGraphics().drawImage(map_png, 200, 200, null);
    Currently the Parameter is being passed into the applet (i've written it out within the applet) but the image is not being displayed. Does anyone have any suggestions about what I'm doing wrong?
    Cheers
    Steve

    hi,
    No, don't get any exceptions, the Java Console has a message:
    <terminated>JavaImageEditor[Java Applet]C:\Program Files\Java\jre1.6.0\bin\javaw.exe
    Cheers
    Steve

Maybe you are looking for

  • Problems playing Echo Pencast pdf,s in Acrobat XI Pro

    Hi I have an Echo smartpen which exports hand written notes containing embedded audio to a pencast pdf. When opening the pencast pdf in acrobat XI Pro you are supposed to get floating audio controls and audio playback as the text turns from green to

  • Report on Internal order

    Hi We have crated an New Internal order and entered the budgeted / planned figures using the KPF6, When we check the  report s_alr_87013017, s alr87013018 and s_alr_87012993 does not show committed. We need a report showing committed spend, actual sp

  • JSP, Javabean charset problem

    I have some JSP pages where I try to dynamically present some drop-down menus for the users to select values. I use a simple bean to manage it. The problem is that those values are in non-iso8859-1 charset and I only get ?????? rendered in the select

  • Excise caputre in GR

    Hi experts i m getting following error when i m doing GR . At the time of Gr i m capturing excise. in the excise tab i m not getting any value of excise duty . all is coming zero. but in PO in taxes tab alll values is coming. ""Excise modvat accounts

  • Sap FS-CD BUSINEE PROCESS

    Hello Experts , Could Anyone tell me the SAP FS-CD  PROCESS  OR SCENARIO Thanks & Regards Balakrishna.