Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / June 2006

Tip: Looking for answers? Try searching our database.

Problem with loading an image to a Panel

Thread view: 
icepac - 21 Jun 2006 04:44 GMT
Salutations everybody.  I want to load an image into a panel. I have
sub-classed the JPanel class in order to be able to override the pain
method, like this :

public class ImageCanvas
   extends JPanel {
 Image image;
 public ImageCanvas() {
   super();
   this.setBackground(Color.white);
 }
 public void paint(Graphics g) {
     if (image!=null)
     {
       g.drawImage(image, 0, 0, this);
     }
 }
 public void SetImage(Image img)
 {
   image = img;
   int iW = Math.min(image.getWidth(this),this.getWidth());
   int iH = Math.min(image.getHeight(this), this.getHeight());

   this.setSize(iW>>1,iH>>1);
   //this.setSize(image.getWidth(this)>>1,image.getHeight(this)>>1);
   setVisible(true);
   this.repaint();
 }

Now I use this code in order to load my image into a normal jPanel :
(this is the snippet of code that executes loading the image :

         //Display images
         Image img =
Toolkit.getDefaultToolkit().createImage(strFilePath);//strFilePath of
course contains the path where the "image.png" is located
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(img, 0);
         try
         {
           tracker.waitForAll();
         }
         catch (InterruptedException exI)
         {
           System.out.println("Error while waiting tracker"+
exI.getMessage());
         }
         jCanvas.setMaximumSize(jPanelImg.getSize());
         jCanvas.SetImage(img);
         jPanelImg.revalidate();  //jPanelImg (type = JPanel) contains
jCanvas which is of type                   //ImageCanvas
         jPanelImg.repaint();

However, when I use this program it loads the image all right but the
background is full of trash.  Also if I try to load multiple images
then they all get jumbled together...
How can I clean this up ?

Thanx alot !
Pascal
Andrew T. - 21 Jun 2006 05:03 GMT
> Salutations everybody.  I want to load an image into a panel. I have
> sub-classed the JPanel class in order to be able to override the pain

'paint'

> method, like this :
>
> public class ImageCanvas
>     extends JPanel {
...
>   public void paint(Graphics g) {
>       if (image!=null)
...

In Swing components you should override paintComponent(),
rather than paint().

BTW there is a more specialised GUI group..
http://groups.google.com/group/comp.lang.java.gui

HTH

Andrew T.
Knute Johnson - 21 Jun 2006 05:41 GMT
>> Salutations everybody.  I want to load an image into a panel. I have
>> sub-classed the JPanel class in order to be able to override the pain
[quoted text clipped - 19 lines]
>
> Andrew T.

You don't need a MediaTracker if you are going to use the Image
Observer/Producer.  It does help if you don't know the size of the image
and need to prepare for it dynamically however.

import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class ImageObserverExample extends Panel {
    Image image;
    String msg = "Loading Image";
    int n;

    public ImageObserverExample() {
        try {
            URL url = new URL(
             "http://www.thealpacastore.com/alpacacam/latest640.jpg");
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            // use createImage instead of getImage - see api docs for why
            image = toolkit.createImage(url);
        } catch (MalformedURLException murle) {
            msg = "MalformedURLException";
        }

        setPreferredSize(new Dimension(400,300));
    }

    public void paint(Graphics g) {
        // show the number of calls to paint()
        System.out.println(++n);
        // if there is an image and drawing has not finished
        // note: if the image is null drawImage will return true
        if (image == null ||
         !g.drawImage(image,0,0,getWidth(),getHeight(),this)) {
            // draw the message
            g.drawString(msg,20,getHeight()/2);
            System.out.println(msg);
         }
    }

    public static void main(String[] args) {
        Frame frame = new Frame("ImageObserverExample");
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });
        ImageObserverExample examp = new ImageObserverExample();
        frame.add(examp,BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}

Signature

Knute Johnson
email s/nospam/knute/

icepac - 21 Jun 2006 16:14 GMT
Thank you alot everybody...
I found my problem.  I am replying in order to give those who have the
same problem the answer:
When you override the paint or paintComponent method you need to make
sure that you still call the super.paint or super.paintComponent.  This
is what you need to fill out your image background in order not to have
too much static...

so the method should go like

 public void paintComponent(Graphics g) {
   super.paintComponent(g);
     if (image!=null)
     {
       g.drawImage(image, 0, 0, this);
     }
 }

And it is indeed better to use paintComponent in Swing ...

C you around ! (Also thanx for redirecting me in the GUI specialised
thread)

P.S. :  Last question, is there a thread specifically used for JFM and
the MediaPlayer ?

Pascal
Andrew T. - 21 Jun 2006 16:57 GMT
..
> P.S. :  Last question,

..yeah, yeah - that's what they all say.   ;-)

>..is there a thread specifically used for JFM and
> the MediaPlayer ?

You mean the JMF?  You might try the forum here..
http://forum.java.sun.com/forum.jspa?forumID=28

HTH

Andrew T.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.