How can i load a BufferedImage to my runnable JAR file? - java

I'm trying to export a JAR file from my project and I need some of my BufferedImages to get loaded in it.
Structure is this:
-src
-img
-models
-views
...
and knowing that all my image files are stored into the img package. I'm trying to do this in a JPanel from other project:
public class BelowPanel extends JPanel {
private BufferedImage img;
public BelowPanel() {
initImage();
setOpaque(false);
}
private void initImage() {
try {
img = ImageIO.read(getClass().getResourceAsStream(("/img/titan.png")));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(img, 0, 0,this.getWidth(),this.getHeight(), this);
}
}
When I run this it shows the image, but once I generate the JAR file in my desktop, it doesn't even run.
My images of Image type, doesn't have any problem, but BufferedImages doesn't load.
So... Do you know a way to load my "titanImage", so I can generate a running JAR file which can work correctly?

Related

Why does my Spaceship not appear?

This is a very simple problem to some people I'm assuming and I just can't see it. (I'm very amateur at Java).
This is some test code I wrote to try and troubleshoot why it's not working in my other project. For some reason my rocketshipStationary.png just won't show up when I load the Java Applet.
This is my code:
public class Test extends Applet {
public Image offScreen;
public Graphics d;
public BufferedImage rocketship;
public void init() {
setSize(854, 480);
offScreen = createImage(854,480);
d = offScreen.getGraphics();
try {
rocketship = ImageIO.read(new File("rocketshipStationary.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
d.clearRect(0, 0, 854, 480);
d.drawImage(rocketship, 100, 100, this);
d.drawImage(offScreen, 0, 0, this);
}
}
You should be getting a nice big stack trace that describes what happens. The bottom line is that 'applets and files do not play well together'.
Instead, either establish an URL to the image and use that for ImageIO, or alternately use the URL in the Applet.getImage(URL) method.

Can't define a path to an image

I imported an image into Eclipse, in the same package as this class:
public class mainWindow extends JFrame {
public mainWindow() {
Image bg = // \mainPackage\ShittyPlane.png;
Graphics2D g2d;
this.setSize(500,500);
this.setResizable(false);
this.setTitle("GameTest");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
g2d.drawImage(bg, 0, 0, null);
}
}
How do I define the image path?
If the image is part of you source and is packed into jar later for distribution i would sucgest you get a stream to the image using getResourceAsStream.
ClassLoader cl = getClass().getClassLoader();
InputStream is = cl.getResourceAsStream("mainPackage/ShittyPlane.png");
BufferedImage image = ImageIO.read(is);
this aproache will also work in if you run the program from your IDE
If you plan to locate the image using a a File chooser then go with #Pescis's answer.
What you need to do to load an image from a specific file is:
BufferedImage img = null;
try {
img = ImageIO.read(new File("src/mainPackage/ShittyPlane.png")); //I'm guessing this is the path to your image..
} catch (IOException e) {
}
For more info you can read the javadoc on working with images.

Display image on applet

I am using Jtree for listing various images of a directory, I want to display image on applet when the user click on the image name displayed in the Tree, the code i'm using is as below, ta is an object of the applet because i'm using it in another class.
private void displayImage(URL furl, String fname) {
ta.Picture = ta.getImage(furl, fname);
prepareImage(ta.Picture, this);
Graphics g = ta.imageCanvas.getGraphics();
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
} // displayImage
public void valueChanged(TreeSelectionEvent e)
{
// TODO Auto-generated method stub
FileTreeNode node = (FileTreeNode) tree.getLastSelectedPathComponent();
System.out.println("slecte asldf " + node.isLeaf());
if (node.isLeaf())
{
currentFile = node.file;
System.out.println("File name " + currentFile.getName());
try
{
URL furl = new URL("file:/F:/photos");
displayImage(furl, currentFile.getName());
}
catch (MalformedURLException mle)
{
System.out.println("Exception::::::" + mle);
}
}
else
currentFile = null;
}
But its not working.
As you are showing files from the local filesystem, working with URLs is not required. Use
displayImage(currentFile);
and rewrite that method as following:
private void displayImage(File file) {
BufferedImage image = ImageIO.read(file);
ta.image = image;
ta.repaint();
}
where the paint method of the (I an assuming) component ta must be like
BufferedImage image;
public void paint(Graphics g) {
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
}
Because of security reasons, the applet will only be able to access the file system if signed or running without security manager (most often on the same computer).
But its not working.
This is in no way helpful, do you get exceptions? What happens? Please post an SSCCE for better help sooner
I want to display image on applet when the user click on the image
name displayed in the Tree, the code i'm using is as below, ta is an
object of the applet because i'm using it in another class.
IMO you are going about it wrong using the JPanel object and Component#getGraphics.
Dont use Component#getGraphics() as its not good practice and not persistent thus on next call to repaint() the screen will be cleared.
Dont use Applet with Swing components rather use JApplet.
Add a custom JPanel with getters and setters for BufferedImage variable to the container and than override paintComponnet and draw the BufferedImage there.
Now to change the BufferedImage simply call the setter i.e setBackgroundImage(BufferedImage img) and than call repaint() on JPanel to show the changes. Like so:
public class MyPanel extends JPanel {
private BufferedImage bg;
public MyPanel(BufferedImage bi) {
bg=bi;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2d.drawImage(bg,0,0,this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(bg.getWidth(),bg.getHeight());
}
public BufferedImage setBackgroundImage(BufferedImage bi) {
bg=bi;
}
}
Now we use it like so:
MyPanel mp=new MyPanel(...);//create the panel with an image
...
add(mp);//add to container
...
mp.setBackgroundImage(..);//change the image being displayed
mp.repaint();//so the new image may be painted

Adding image to JPanel through ImageIO.read?

I'm trying to add a JPanel with a picture in it. I'm using ImageIO.read to get the path but i get an IOException saying : can't read input file
The picture is called TCHLogo. It's a PNG inside a 'res' folder inside my project.
If there is any better way of displaying this image please also mention it!
Here is the code for my JPanel:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
//THIS LINE BELLOW WAS ADDED
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
} catch (IOException ex) {
// handle exception...
System.out.println(ex);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g); //THIS LINE WAS ADDED
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
Here is how i add the JPanel in my Applet:
ImagePanel appletRunningPanel;
appletRunningPanel = new ImagePanel();
appletRunningPanel.setSize(300, 300);
appletRunningPanel.validate();
add(appletRunningPanel);
EDIT
I created a folder inside the bin which the application starts to look in currently..
the folder is called res and the picture is inside..
Now i get the following IOException when i run the line:
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
Here is the error log:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1338)
at surprice.applet.ImagePanel.<init>(ImagePanel.java:17)
at surprice.applet.MainClass.init(MainClass.java:41)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:679)
Likely your image's file path isn't correct relative to the user directory. To find out where Java is starting to look, where the user directory is, place something like this line of code somewhere in your program:
System.out.println(System.getProperty("user.dir"));
Perhaps you'd be better off getting the image as an InputStream obtained from a resource and not as a file. e.g.,
image = ImageIO.read(getClass().getResourceAsStream("res/TCHLogo.png"));
This will look for the image at the path given relative to the location of the class files, and in fact this is what you must do if your image is located in your jar file.
Edit 2
As an aside, often you need to first call the super's paintComponent method before doing any of your own drawing so as to allow necessary house-keeping can be done, such as getting rid of "dirty" image bits. e.g., change this:
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
to this:
public void paintComponent(Graphics g) {
super.paintComponent(g); // **** added****
g.drawImage(image, 0, 0, null);
}
I've written this ImagePanel class that i use for this scope :
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 7952119619331504986L;
private BufferedImage image;
public ImagePanel() { }
public ImagePanel(String resName) throws IOException {
loadFromResource(resName);
}
public ImagePanel(BufferedImage image) {
this.image = image;
}
#Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
/**
* Load the Image from a File
* #param path image name and path
* #throws IOException
*/
public void loadFromFile(String path) throws IOException {
image = ImageIO.read(new java.io.File(path));
}
/**
* Load Image from resource item
* #param resName name of the resource (e.g. : image.png)
* #throws IOException
*/
public void loadFromResource(String resName) throws IOException {
URL url = this.getClass().getResource(resName);
BufferedImage img = ImageIO.read(url);
image = img;
}
}
Then i use the ImagePanel in this way :
//Inizialization of the ImagePanel
ImagePanel panelImage = new ImagePanel();
//Try loading image into the image panel
try {
panelImage.loadFromResource("/Resources/someimage.png");
} catch (java.io.IOException e) {
//Handling Exception
}

How do I make an Image show up in a Java Swing Applet

How do I make an Image show up in a Java Swing Applet?
The simplest way is to add it as an Icon to a JLabel that you put on your GUI.
http://download.oracle.com/javase/6/docs/api/javax/swing/JLabel.html#JLabel(javax.swing.Icon)
Here's an outline of what you need
class myApplet extends JApplet {
private BufferedImage image;
myApplet() {
try {
image = ImageIO.read(new File("insert image path here"));
} catch (IOException ex) {
// handle exception...
}
}
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}

Categories

Resources