Need to display image on JPanel

Hello
I am trying to implement a graphical version of the Knights Tour. I am done with the algorithm part of the problem itself. I am having problem with displaying the chess board. Although seemingly straightforward the images will not display on the JPanel. Below is a sample of what I am trying to do. Can anyone explain why the code does not work even though it seems okay. Thanks and best regards.
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
public class test extends JFrame { 
public test(){ 
panel pane = new panel();
getContentPane().add(pane);
public static void main(String[]args){   
test tst = new test();
tst.setSize(500,500);
tst.show();
public class panel extends JPanel{   // inner class
private Image img;
private ImageIcon icon;
public panel(){
icon = new ImageIcon("cross.gif");
img = icon.getImage();
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
System.out.println("I am here");
g.drawImage(img,40,40,this);
}

package com.lc.util.swing ;
import java.awt.Color ;
import java.awt.Graphics ;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Dimension ;
import java.awt.image.ImageObserver ;
import javax.swing.JPanel;
import javax.swing.border.Border;
* Panel displaying an {@link Image}.
* <ul>
* <li>8 positions,</li>
* <li>
* can stretch image for filling the whole available area, or diminish
* its size if too large in width or height,
* </li>
* <li>respects borders (as defined by
* {@link javax.swing.JComponent#setBorder( javax.swing.border.Border ) JComponent.setBorder}
* </li>
* </ul>
* @author Laurent Caillette
* @version $Revision: 1.1.1.1 $ $Date: 2002/02/19 22:12:04 $
public class JImagePanel extends JPanel {
public JImagePanel() {
imageObserver = this ;
* Constructeur assignant une image.
public JImagePanel( Image image ) {
this() ;
setImage( image ) ;
private Image image ;
private ImageObserver imageObserver ;
public void setImage( Image image ) {
this.image = image ;
adjustPreferredSize();
public void setBorder( Border newBorder ) {
super.setBorder( newBorder ) ;
adjustPreferredSize() ;
private void adjustPreferredSize() {
if( image != null ) {
int w = image.getWidth( imageObserver ) ;
int h = image.getHeight( imageObserver ) ;
Border border = getBorder() ;
if( border != null ) {
Insets insets = border.getBorderInsets( this ) ;
if( insets != null ) {
w += ( insets.left + insets.right ) ;
h += ( insets.top + insets.bottom ) ;
Dimension dim = new Dimension( w, h ) ;
this.setPreferredSize( dim ) ;
private int placement = CENTER ;
public int getPlacement() { return placement ; }
public void setPlacement( int placement ) {
if( ( placement < CENTER ) || ( placement > STRETCH ) ) {
throw new IllegalArgumentException( "Unsupported placement value" ) ;
this.placement = placement ;
public void paint( Graphics gr ) {
// x of Image to draw
int x ;
// y of Image to draw
int y ;
// width of Image to draw
int iw ;
// height of Image to draw
int ih ;
// thickness of left border
int bl = 0 ;
// thickness of upper border
int bt = 0 ;
// thickness of right border
int br = 0 ;
// thickness of lower border
int bb = 0 ;
// width of drawable area
int pw = this.getWidth() ;
// height of drawable area
int ph = this.getHeight() ;
// Handle borders
Insets insets = null ;
Border border = getBorder() ;
if( border != null ) {
insets = getBorder().getBorderInsets( this ) ;
if( insets != null ) {
bl = insets.left ;
br = insets.right ;
bb = insets.bottom ;
bt = insets.top ;
pw = pw - bl - br ;
ph = ph - bt - bb ;
// Always display background, for supporting transparency.
super.paint( gr ) ;
if( image != null ) {
iw = image.getWidth( imageObserver ) ;
ih = image.getHeight( imageObserver ) ;
if( ( placement == STRETCH ) ||
( iw > pw ) ||
( ih > ph )
gr.drawImage(image, bl, bt, pw, ph, imageObserver ) ;
} else {
iw = image.getWidth( imageObserver ) ;
ih = image.getHeight( imageObserver ) ;
switch( placement ) {
case CENTER :
x = ( pw - iw ) / 2 ;
y = ( ph - ih ) / 2 ;
break ;
case NORTH :
x = ( pw - iw ) / 2 ;
y = 0 ;
break ;
case NORTHEAST :
x = pw - iw ;
y = 0 ;
break ;
case EAST :
x = pw - iw ;
y = (ph - ih ) / 2 ;
break ;
case SOUTHEAST :
x = pw - iw ;
y = ph - ih ;
break ;
case SOUTH :
x = ( pw - iw ) / 2 ;
y = ph - ih ;
break ;
case SOUTHWEST :
x = 0 ;
y = ph - ih ;
break ;
case WEST :
x = 0 ;
y = ( ph - ih ) / 2 ;
break ;
case NORTHWEST :
x = 0 ;
y = 0 ;
break ;
default :
throw new IllegalArgumentException(
"Unsupported placement value" ) ;
// Add border offset
x += bl ;
y += bt ;
gr.drawImage( image, x, y, this ) ;
public final static int CENTER = 0 ;
public final static int NORTH = 1 ;
public final static int NORTHEAST = 2 ;
public final static int EAST = 3 ;
public final static int SOUTHEAST = 4 ;
public final static int SOUTH = 5 ;
public final static int SOUTHWEST = 6 ;
public final static int WEST = 7 ;
public final static int NORTHWEST = 8 ;
public final static int STRETCH = 9 ;

Similar Messages

  • Two problems with displaying images in JPanel

    Hi,
    I need to display some small rectangular images inside a JPanel. These images also need to be componenents as they will have listeners associated with them. I have never had any experience with images, so I might totally be down the wrong path. I was thinking of just creating a class which extends JComponent, and using the graphics drawImage method. However, I don't want each image component to have to know exactly where to draw the image associated with itself. Rather, I want the JPanel which holds all of the images to know how to lay them out.
    Is there an easier way to use images?
    Which brings me to my second problem. I want these images to overlap each other, so that only a small portion of each is showing (this way I can fit more on the screen), then when the user clicks on one, I can show more of it.
    Unfortunately, I don't know of any layout managers which will allow me to overlap components. I could use the drawImage method mentioned above, but like I said, I would like to try to not have each image object try and figure out its location.
    any help is greatly appreciated. Thanks!

    Hi
    there is a better way ; it is called a JLabel ;-)
    JLabel myJLabel = new JLabel(new ImageIcon("img/myLogo.gif"));for your second problem, don't use any layout manager like in this code :
    myJPanel.setLayout(null);
    myJPanel.add(myJLabel);
    myJLabel.setBounds(new Rectangle(x, y, width, height);hope it helps
    Nico

  • 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

  • Displaying image in JPanel and scroll it through JScrollpanel

    Can any one will help me,
    I need to draw a image in a JPanel and, this JPanel is attached with a Jscrollpanel.
    I need to scroll the this JPanel to view the image.

    Here is my code for that
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PicPanel extends javax.swing.JPanel implements WindowListener{
    /** Creates new form PicPanel */
    public PicPanel() {
    initComponents();
    // this.setOpaque(true);
    JFrame myFrame = new JFrame("Panel Tiler");
    myFrame.addWindowListener( this );
    myFrame.setSize(new Dimension(1000,300));
    setPreferredSize(new Dimension(1000,300));
    Container cp = myFrame.getContentPane();
    cp.add( this, BorderLayout.CENTER );
    tk = Toolkit.getDefaultToolkit();
    im =tk.getImage("smple.jpg");
         jPanel1.im=im;
    // jPanel1.setSize(new Dimension(1000,300));
    myFrame.pack();
    myFrame.show();
    jPanel1.repaint();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;
         jPanel1=new JPanelC();
    jScrollPane1 = new javax.swing.JScrollPane(jPanel1);
    setLayout(new java.awt.GridBagLayout());
    jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setOpaque(false);
         gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.gridheight = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.ipadx = 378;
    gridBagConstraints.ipady = 298;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    add(jScrollPane1, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.ipadx = 372;
    gridBagConstraints.ipady = 280;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    add(jPanel1, gridBagConstraints);
    public static void main(String[] args)
    new PicPanel();
    public void windowOpened(WindowEvent e) {}
    public void windowClosing(WindowEvent e)
    // myFrame.dispose();
    System.exit(0);
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    private JPanelC jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private Icon iiBackground;
    private Toolkit tk;
    private Image im;
    class JPanelC extends javax.swing.JPanel{
    public Image im;
    public void paintComponent(Graphics g){
              //super.paintComponent(g);
    if(im!=null)
                   imageobserver io = new imageobserver();
         System.out.println(im.getHeight(io));
         if(im.getHeight(io)!=-1)
    setSize(im.getWidth(io), im.getHeight(io));
    g.drawImage(im,0,0,null);
         // setOpaque(false);
    super.paintComponent(g);
    class imageobserver implements java.awt.image.ImageObserver{
    public boolean imageUpdate(Image img, int infoflags, int x, int y,int width, int height) {
              if ((infoflags & java.awt.image.ImageObserver.ALLBITS) != 0) {
    repaint();
    return false;
    //repaint();
    return true;
    Here i need to scroll the image in the panel but it is not working out.

  • 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();

  • Display image using JPanel

    i have got buffered image from webcam using jmf. i want to display it on JPanel.
    i override paint() but it doesn't display as it captures
    when i maximize window it then displays
    urgent help needed

    The bounds of your JPanel may be incorrect. You should try the setBounds(int x, int y, int width, int height) method on it.
    Please past your code for more help :p

  • 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

  • Need help displaying images with List component for Flash CS4 (ActionScript 3.0)

    Hi folks:
    I am an inexperienced user of Flash CS4 Pro (v10.0.2). I am attempting to use the List component with ActionScript 3.0 to make a different image display when a user clicks each item in a list.
    I did find a tutorial that showed me how to make different text display using a dynamic text box and the following ActionScript:
    MyList.addEventListener(Event.CHANGE, ShowSelectedItem);
    function ShowSelectedItem(event:Event):void {
        ListText.text=MyList.selectedItem.data;
    ...where My List is the instance of the List component and ListText is the dynamix text box. In this case, the user clicks an item in the list, defined by the label value in the dataProvider parameter of the List component, and text displays as defined in the data value in the dataProvider parameter.
    However, as I mentioned to start, what I really want to do is make images display instead of text. Can anyone provide me the steps to do this?
    I appreciate your help (in advance)!!
    Cindy

    Hi...thanks for responding! I was planning on using images from the Library, but if there is a better way to do it, I'm open. So far, I just have text in the data property. This is part of my problem. I don't know what I need to put in the data value for an image to display. Do I just put the image file name and Flash will know to pull it from the Library? Do I need to place the images on the stage on different frames? I apologize for the "stupid user" questions, but as you can tell, I'm a newbie.
    Appreciate your patience and any help you can offer!
    Cindy

  • Displaying images in JPanel

    Hi,
    I'm trying to work out the best method to display a set of thumbnail images in a JPanel (similar to a Thumbnail view in windows XP) - at the moment I'm using a Tree, but am wondering whether this is the best way to go about it? I'm using a tree in combination with a TreeModel but am having some problems as the cells don't expand to fit the picture size. Any ideas appreciated!!
    thanks
    Jonathan

    Why dont you use a JTable?

  • Problems displaying image in JPanel

    Hi, 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

    Hello,
    after an update of the graphics card driver to the newest just released version the problem has vanished.
    Regards

  • Simple and efficient way to display image on jpanel

    AOA
    What may be the simple and efficient way
    to display a strored jpg image on a jpanel in an application.
    i will appreciate more than one ways.
    thanks

    JPanel panel = new JPanel() {
         public void paintComponent(Graphics g) {
                   g.drawImage(......);
    };

  • 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);
    }

  • Need help displaying image on canvas  :((

    can anybody help me with my coding. my problem is, i cannot display an image on my canvas. plz..someone help me to solve my problem..
    Here's my coding...
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.*;
    import java.util.*;
    public class ImageMidletServlet
        Display display = null;
        //Form f = null;
        String url = "http://localhost:8080/banner/hp0.gif";
        String url2 = "http://localhost:8080/banner/rotateNumber";      
        //String url = "http://localhost:8080/banner/banner";
        Command backCommand = new Command("Back", Command.BACK, 0);
        Command submitCommand = new Command("Submit", Command.OK, 2);
        Command exitCommand = new Command("Exit", Command.STOP, 3);
        private Test test;  
        private StringItem stringItem2;
        private TextField txtField;
        private Timer tm;          // Timer
        private load load;       // Task
        private int id = 0;
        Image img = null;
        //String id;
        public ImageMidletServlet(Display display)
            this.display=display;  
            loadimage();
        public void loadimage()
            tm = new Timer();
            load = new load();
            tm.schedule(load,0,6000);
         class Test extends Canvas implements Runnable, CommandListener
            private Canvas canvas;
            public Test(Canvas canvas)
                this.canvas=canvas;
                setCommandListener(this);
            public void start()
                Thread t = new Thread(this);
                t.start();
            public void run ()
                DataInputStream is = null;
                DataInputStream is2 = null;
                StringBuffer sb = new StringBuffer();
                Image img= null;
                TextBox txtBox = null;
                StringBuffer b = new StringBuffer();
                HttpConnection c2 = null;
                OutputStream os = null;           
                ++ id;
                try
                    c2 = (HttpConnection)Connector.open(url2+ "?bannerid="+id);
                    os = c2.openOutputStream();
                    os.write(("bannerid="+id).getBytes());              
                    os.flush();
                    //HttpConnection c = (HttpConnection) Connector.open(url+ "?bannerid="+id);
                    HttpConnection c = (HttpConnection) Connector.open(url);
                    int len = (int)c.getLength();
                    if (len > 0)
                        is = c.openDataInputStream();
                        byte[] data = new byte[len];
                        is.readFully(data);
                        is2 = c2.openDataInputStream();
                        int ch;
                        while ((ch = is2.read()) != -1) {
                        b.append((char) ch);
                        System.out.print((char)ch);
                        try {
                        //img = Image.createImage(data, 0, len);
                        img = Image.createImage("/images/splash.png");
                        Graphics graphics = img.getGraphics();                   
                        catch (Exception e)
                        if(img==null)
                        System.out.print("no image");
                        else {System.out.print("got image");}
                    else
                        showAlert("length is null");;
                    is.close();
                    c.close();
                    c2.close();
                   // repaint();
                catch (Exception e)
                    e.printStackTrace();
                    showAlert(e.getMessage());
            /* Display Error On screen*/
            private void showAlert(String err)
                Alert a = new Alert("");
                a.setString(err);
                a.setTimeout(Alert.FOREVER);
                display.setCurrent(a);
             public void commandAction(Command c, Displayable d)
            if (c == exitCommand)
                //destroyApp(true);
                //notifyDestroyed();
            else if (c == backCommand)
                //display.setCurrent(f);
            else if (c == submitCommand)
                /*test  = new Test(this);
                test.start();*/
             protected void paint(Graphics graphics)
             if (img != null)
                graphics.setColor(0x000000);  
                graphics.drawImage(img, 0, 0, Graphics.TOP | Graphics.HCENTER);
             else
             {System.out.print("no drawing");}
        class load extends TimerTask
        private Test canvas;
           public final void run()
          this.canvas = canvas;
          test  = new Test(canvas);
          //test();
          test.start();
    }

    Hi
    I would do like this: take the code that draws the image an put it into a separate class (which will extend the Canvas class) which will take as a parameter to its constructor either an array of bytes or an Image object (it's up to you) and call this class after you have downloaded all the bytes from the input stream. I presume that you get the "no drawing" message..
    Mihai

  • Displaying Image on JPanel

    Hello, I am having problems trying to display an image on a Panel which is attached to a Frame. I can display an Image on the Frame with no difficulty, however nothing appears when I try to draw on the Panel.
    Hope someone can help me with this.
    Here is the code
    import java.awt.*;
    import java.awt.event.*;
    class TestFrame extends Frame
         Panel panel;
         public TestFrame()
             setSize(400,400);
             panel = new Panel();
             add(panel);
         public class panel extends Panel
             Image img;
             public panel()
                 setSize(400,400);
              setVisible(true);
              img = Toolkit.getDefaultToolkit().getImage("C:\\red.gif");
             public void paint(Graphics g)
              g.drawImage(img,0,0,this);
         public static void main (String[] args)
             TestFrame f = new TestFrame();
             f.setVisible(true);
    }

    I took a look on your code and I find that 2 things might be wrong with it. See the comments below.
    import java.awt.*;
    import java.awt.event.*;
    class TestFrame extends Frame
         Panel panel;
         public TestFrame()
             setSize(400,400);
         panel = new Panel(); /****You created a Panel object from the the awt package and not an object from the panel class that you defined below. Try using panel= new panel(); or use a anonymous class for this purpose. The picture will never show because it is not using the class that you defined************/
         add(panel);
         public class panel extends Panel /*******Try giving the panel class that you defined another name so as to not confuse you with java.awt.Panel classs. ********/
         Image img;
         public panel()
         setSize(400,400);
              setVisible(true);
    img =
    =
    Toolkit.getDefaultToolkit().getImage("C:\\red.gif");
         public void paint(Graphics g)
              g.drawImage(img,0,0,this);
         public static void main (String[] args)
         TestFrame f = new TestFrame();
         f.setVisible(true);
    }Below is a panel class that i think can help. Just pass the appropriate parameters to it.
    //container class for the image panel
    public class ImagePanel extends Panel {
    Image image;
    public ImagePanel(Image image) {
    this.image = image;
    // display the image
    public void paint( Graphics g )
    // draw the original image
    g.drawImage( image, 1, 1, this );

  • How to display  image efficiently in JPanel.............

    i have following piece of code used to load and display image on jpanel when application starts.
    the problem is that
    image is not loaded efficiently,
    also it covers other panels added in frame.
    and scrollbar of panel does not work to show parts of image.
    i want to efficiently load the image and to fit in in my panel and also to scroll bar to work proper with image.
    looking for any nice suggestion
    public class MainFrame extends JFrame
    Image image = Toolkit.getDefaultToolkit().createImage("c:\\form-3.jpg");
    javax.swing.JScrollBar jScrollBar1 = new JScrollBar();
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel jPanel1 = new JPanel();
    JPanel jPanel2 = new JPanel();
    JButton jButton1 = new JButton();
    JButton jButton2 = new JButton();
    public MainFrame()
    try
    {            jbInit();        } catch (Exception ex)
    {            ex.printStackTrace();        }
    public static void main(String[] args)
    MainFrame mainFrame = new MainFrame();
    jBInit Method defined here
    public void paint(Graphics g)
    g.drawImage(image,0,0,jPanel1);
    Message was edited by:
    @tif

    You have overided the paint method on JFrame then you are drowing on entire Frame.
    Instead you have to override the paintComponent method of a JPanel class or use a JLabel with the image

Maybe you are looking for

  • After downloading iTunes 7.4.1 - Can not access iTunes Music Store

    After downloading iTunes 7.4.1, I am unable to access the iTunes Music Store. When I try to open the store, an error message appears saying _*iTunes could not connect to the iTunes Store. An unknown error has occured (-3212) Make sure your connection

  • How can I deselect ColorSync

    I am trying to print a color test chart and it requires ColorSync not be selected. When I get into the print menu and select Color it is locked on ColorSync and greyed out. I can't find a way to select Vendor Control. Any ideas?

  • Social Media Trends for 2014 - Have you noticed them?

    Recently I have been conducting some research on Social Media trends that have grown in popularity especially this year and look likley to continue to grow. Here are the top 5 trends that most experts recognise as an area of focus for all social medi

  • Dreamweaver cs5.5 stopped working.

    Since yesterday, my dreamweaver cs5.5 stopped working, Now, whenever I open dreamweaver, it shows this pop out box. Does anyone know how to fix this?

  • Bihar Professional Tax

    Hi Any SAP Notes released for new amendment of Bihar Professional Tax or to be addressed by cutomizing Pls reply with regards Partha Keep sharing and learning