Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to add a JPEG to JPanel

Status
Not open for further replies.

sparafucile17

Programmer
Apr 5, 2002
40
US
Can anyone give me a quick couple lines of code for adding a JPEG image to JPanel? I need to put a comany logo in my JPanel, but can't find any definitive way to do it. I got as far as creating a Toolkit and opening and Image from it. But now how to I place it on the panel? Currently the whole panel is laid out using x-y coordinates, so merely placing it "North" or "South" doesn't do me any good.

I really need a way to place it using x-y coordinates and to make it visible.

Is using a Toolkit and Image the right way to add a JPEG? Am I on the right track?

All suggestions are welcome.
 
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
 
Ok this works, but ONLY after a button is clicked or some other GUI command tries to repaint the screen. Initially, the JPG is not visible. Is there something I can do to load it on initial startup?

Just to clear things up a little... here is exactly what I'm doing:

class myPanel extends JPanel {

Image Logo;

public myPanel() {
//more stuff
Toolkit tk = Toolkit.getDefaultToolkit();
Logo = tk.getImage("WorkLogo.jpg");
}

public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(Logo, 100, 100, null);
}
}

----------------------------------------------
Then in my main JFrame I do this:
----------------------------------------------

public class mainWindow extends JFrame {

javax.swing.JPanel JPanel1 = new javax.swing.JPanel();

public mainWindow() {
setTitle("My Window");
JPanel1.add(myPanel);
pack();
}

public static void main(String args[])
{
mainWindow mw = new mainWindow();
mw.setSize(800, 600);
mw.show();
}
}


Does this help any?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top