Skip to main content
GameDev.net gamedev.net
šŸ”’ Locked

[java] Displaying JPEGs in a Java application

Started by GGamer Oct 28, 2002 at 7:07 PM 2 replies 250+ views
Original Post
GGamer
GGamer
Is there a simple way to display a jpeg or GIF in a java application, is inside a jPannel? Thanks in advance
CaptainJester
CaptainJester
Toolkit t=Toolkit.getDefaultToolkit();
Image i=t.getImage("myimage.jpg");


public void paint(Graphics g) {
g.drawImage(i,0,0,this);
}


That is without looking at the docs. You might want to check them to make sure I have the right methods.



Make it work, then
make it fast.

"I’m happy to share what I can, because I’m in it for the love of programming. The Ferraris are just gravy, honest!" --John Carmack: Forward to Graphics Programming Black Book
"None of us learn in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!" - Michael Abrash[JavaGaming.org][The Java Tutorial][Slick][LWJGL][
GGamer
GGamer
That compiled OK except I didn''t see anything, infact it got rid of the otheritems in the window. I think it is the way I used the paint method and the graphics class.

I will hev to investigate,

Thanks
cyrax256
cyrax256
You are using Swing, the correct way would be this:


  
import java.awt.Toolkit;
import java.awt.*;
import javax.swing.*;

class NicePanelClass extends JPanel { //Note that this is the JPanel, you would have to add this panel in the ContentPane of a JFrame


//In the initialization of the images

Toolkit tk = Default.getDefaultToolkit();
Image img = tk.getImage("MyNiceImage.jpg"); //or gif, or png, it reads popular extensions

//Rest of initialization


public void paintComponent(Graphics g) { //For swing panels, you have to rewrite this method

super.paintComponents(g); //This is important, if you forget this, when you start drawing your image the rest of the components will disappear


g.drawImage(img, 5, 5, this);
}
}


Hope that helps

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.