Problem in displaying image on jpanel..............``

i want to display image on jPanel1 through following code but its not working. kindly point out the problem.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

class MainFrame extends JFrame

{

Image image = Toolkit.getDefaultToolkit().createImage("c:\\form-3.jpg");

public static JPanel jPanel1 = new JPanel();

public static void main(String[] args)

{

MainFrame mainFrame = new MainFrame();

mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

mainFrame.add(jPanel1);

mainFrame.setSize(200,200);

mainFrame.setVisible(true);

}

public void paintComponent(Graphics g)

{

jPanel1.paint(g);

g.drawImage(image,15,15,jPanel1);

}

}

[819 byte] By [@tifa] at [2007-10-2 21:36:12]
# 1

you're abusing the paintComponent method of JFrame when you do this. This is what is happening:

first, the system tells Jcomponent to paint its contents. so you call jPanel1.paint(which paints an empty JPanel, filling it's area in with the background color of the JPanel). Then When you pass the JPanel as a parameter to g.drawImage, that does not mean that it is drawing to the panel, that means that it is using the panel as an image observer.

anyway, after you draw the image, the JFrame will then make a call to paintChildren, which calls JPanel.paint.

The very first thing JPanel.paint does if the jpanel is opaque is to completely fill in it's area with the background color. So the image may well be being drawn in the frame, but then the JPanel is drawing over top of it.

What you need to do is create a Sub-Class of JPanel, override ITS paintComponent method to render the image. Then add that JPanel to the frame. Don't bother overriding JFrame's paintComponent method at all. That should fix your problem.

Something like this:

class MainFrame extends JFrame {

Image image = Toolkit.getDefaultToolkit().createImage("c:\\form-3.jpg");

public static JPanel jPanel1 = new JPanel() {

public void paintComponent(Graphics g) {

g.drawImage(image,15,15,jPanel1);

}

};

public static void main(String[] args) {

MainFrame mainFrame = new MainFrame();

mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

mainFrame.add(jPanel1);

mainFrame.setSize(200,200);

mainFrame.setVisible(true);

}

}

- Adam

guitar_man_Fa at 2007-7-14 0:50:21 > top of Java-index,Java Essentials,New To Java...
# 2
Apolegies in advance for being pedantic, using a JComponent rather than a JPanel would be more efficient and give the same result.Bamkin
bamkin-ov-lestaa at 2007-7-14 0:50:21 > top of Java-index,Java Essentials,New To Java...
# 3
> Apolegies in advance for being pedantic, using a> JComponent rather than a JPanel would> be more efficient and give the same result.> > BamkinYes, very true. I was just trying to keep it simple for the OP.- Adam
guitar_man_Fa at 2007-7-14 0:50:21 > top of Java-index,Java Essentials,New To Java...