-
importing jpegs/bmps onto jPanels
Hi, I'm designing a GUI which consists of various frames, some of which have Jpanels on them. My question is, how do I go about importing a jpeg onto that panel. I know I need to use ImageIcon, but I have no idea where to start with regards to code. Any help would be great!!!
-
You don't _import_ images into panels, you read the image files (FileInputStream as bytes), convert the contents to Image, override the paint method of the coponent that will render the image and do a g.drawImage there. If you plan on doing animation (fast image sequences) you'll have to override the update method of the component, using a second image (in memory) that you draw on, and draw this image in the update method. If you don't the animation will look like a bad tv reception.
eschew obfuscation
-
Here's how you read an image file and convert it to an image:
import java.awt.Image;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class GetImageFromFile {
public Image getImageData (String filePath, JFrame pFrame) {
try {
FileInputStream fi=new FileInputStream(filePath);
byte [] imageBytes=new byte[fi.available()];
fi.read(imageBytes);
fi.close();
Image img=Toolkit.getDefaultToolkit().createImage(imageBytes);
MediaTracker mt=new MediaTracker(pFrame);
mt.addImage(img,0);
try {
mt.waitForID(0); // cant use it until it's ready....
} catch (InterruptedException ex) {
ex.printStackTrace();
return null;
}
return img;
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
}
eschew obfuscation
-
Thanks for your help! Now that I can convert the image file into an actual image, how can I paint that image onto a JPanel in one of my frames-i.e what code do I need to use?
-
You override the components paint method.
Check my answer on another paint problem.
If you just want to paint an image you don't have to go as far as in that example. Just do a plain drawImage in the paint method;
g.drawImage(img, 0,0, thePanel);
Just to state the obvious, you have to extend the component type that you want to paint in.
eschew obfuscation
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks