How to get resources working in runnable jar? - java

I have a Image Icon in my Jframe.I am using a Image in it.When i export into a Runnable Jar.The Image is Not displayed.
String iPath = "res/images/Mobile.png";
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, 315, 610);
InputStream stream = (InputStream) getClass().getResourceAsStream(iPath);
JLabel mobileImageLabel;
mobileImageLabel = new JLabel(new ImageIcon(iPath));
//mobileImageLabel = new JLabel(new ImageIcon(ImageIO.read(stream)));
// mobileImageLabel = new JLabel(new ImageIcon(AppFrame.class.getResource(iPath)));
mobileImageLabel.setBounds(0, 0, 315, 610);
mobileImageLabel.setVisible(true);
layeredPane.add(mobileImageLabel, Integer.valueOf(0));
I googled & found the getResourceAsStream method.But it seems to throw NullPointerException.
So Help me in the Right Direction :)
Thanks for your Help ...
Note
The Method i Tried has been Commented

To set a image in a button I did this:
JButton yourButton = new JButton("text button");
try {
yourButton.setIcon(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/icon-for-your-button.png"))));
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
You must have the images inside your project like this:
In your case, the answer I think is to do this:
new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/icon-for-your-button.png")))

Try to replace
String iPath = "res/images/Mobile.png";
By
String iPath = "C:/..../res/images/Mobile.png";
Whenever you are working with images try to put the complete path for the image. So when you will generate your .jar file and try to run it from different place(may be possible that you want the jar should be run from desktop) you will get all the images.

Related

Add a button menu to javahelp

In my program, I'm using javahelp with helpbroker: all the swing components of the window are automatically generated and positioned.
I would like custom the helpbroker to add a button bar at the bottom of the window like in the image.
What is the easiest way to do it ?
Thanks
The only way to add a help button is to Embed the javahelp in a JFrame:
public class vmHelp {
public static void main(String args[]) {
JHelp helpViewer = null;
String title = "";
try {
// Get the classloader of this class.
ClassLoader cl = vmHelp.class.getClassLoader();
// Use the findHelpSet method of HelpSet to create a URL referencing the helpset file.
// Note that in this example the location of the helpset is implied as being in the same
// directory as the program by specifying "jhelpset.hs" without any directory prefix,
// this should be adjusted to suit the implementation.
String lHelpSetFile = "APP.hs";
URL url = HelpSet.findHelpSet(cl, lHelpSetFile);
if (url == null) {
System.err.println("URL is null, maybe the help set file is wrong: " + lHelpSetFile + ". Look at vmHelp.java");
return;
}
// Create a new JHelp object with a new HelpSet.
HelpSet h = new HelpSet(cl, url);
title = h.getTitle();
helpViewer = new JHelp(h);
// Set the initial entry point in the table of contents.
helpViewer.setCurrentID("top");
} catch (Exception e) {
System.err.println(e.getMessage());
}
// Create a new frame.
JFrame frame = new JFrame();
// Set it's size.
frame.setSize(1000, 800);
// Add the created helpViewer to it.
frame.getContentPane().add(helpViewer);
// Set a default close operation.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(title);
// Make the frame visible.
frame.setVisible(true);
}
}
After we can customize the JFrame as we want, it is easy to add a south panel with a close button.
To make all the help buttons listen our javahelp:
pButton.addActionListener(helpAction(pHelpId));
with helpAction that displays our JFrame
Think also to handle keyboard shortcuts, like the helpbroker:
pComponent.registerKeyboardAction(helpAction(pHelpId), KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
pComponent.registerKeyboardAction(helpAction(pHelpId), KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
To open the help at the wanted section:
helpViewer.setCurrentID("top");
"top" corresponds to tag in the .jhm file

Error showing images in applet in browser

I'm new to Java Applets and I have a little problem.
I need to load and display images in applet loaded in browser.This is part of the code i'm using to display image:
Panel first=new JPanel();
URL url = null;
try {
url = new URL(new URL(path),"Dell_laptop.jpg");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Image img = getImage(url);
ImageIcon fimg = new ImageIcon(img);
JLabel jLabel1=new JLabel(fimg);
first.add(jLabel1);
So when it's working in eclipse, it's working flawless.But when i'm trying to load this same applet in HTML page, it's not working.Applet is loaded,but images aren't shown.Path is correct, checked it.

Loading images from jar files (Using Eclipse IDE)

I've got a simple swing application with a JFrame that holds various components. On the JFrame I have a custom toolbar class that extends JPanel. On the JPanel I plan on adding buttons with image icons. My directory structure is as follows:
Project/src/gui (Package holds source files for application)
Project/src/images (Package holds a jar file jlfgr-1_0.jar with button icons and /or individual images files)
The issue is that I want to avoid copying the individual image files to the images package. I'd rather somewhow just load the images directly from the jar file. I've got private method that returns the appropriate icon. This method works, for example if I drag an image file to the images package and call:
button.setIcon(createIcon("/images/Save16.gif"));
private ImageIcon createIcon(String path) {
URL url = getClass().getResource(path);
ImageIcon icon = new ImageIcon(url);
if(url == null) {
System.err.println("Unable to load image: " + path);
}
return icon;
I know this is basic, but how can I get my images directly from the jar file in my current setup?
Thanks.
You can read the image from the stream, thanks to javax.imageio.ImageIO:
private ImageIcon createIcon(String path) {
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
ImageIcon icon = new ImageIcon(image);
return icon;
}
This is another way. The images are at location src/images
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(this.getClass().getResource("images/Picture2.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
try {
myPicture = ImageIO.read(this.getClass().getResource("images/broken_image.jpg"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
panel.add(picLabel);

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.

Hows to open an .bmp/.jpeg image using Java

I am working on a JFrame/panel that will contain a button. When the user clicks the button, I want an image (which will be stored in the computer hard disk beforehand) to open on the front screen.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//here i want a code that will somehow open the image from a given directory
}});
Any suggestions on how to go about this ? I have to tell where the image is stored and trigger a virtual 'double click' for the image to pop up on the front screen. Is that even possible using java to synchronize such computer functions?
I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try {
// this is a new frame, where the picture should be shown
final JFrame showPictureFrame = new JFrame("Title");
// we will put the picture into this label
JLabel pictureLabel = new JLabel();
/* The following will read the image */
// you should get your picture-path in another way. e.g. with a JFileChooser
String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
/* until here */
// add the image as ImageIcon to the label
pictureLabel.setIcon(new ImageIcon(img));
// add the label to the frame
showPictureFrame.add(pictureLabel);
// pack everything (does many stuff. e.g. resizes the frame to fit the image)
showPictureFrame.pack();
//this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
showPictureFrame.setVisible(true);
}
});
} catch (IOException ex) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(ex.getMessage());
}
I think this will work ...
Code:
process = new ProcessBuilder("mspaint","yourFileName.jpeg").start();
This will open your image file with mspaint.....
and also use *Java Advanced Imaging (JAI)*
Try this code
try
{
// the line that reads the image file
BufferedImage image;
// work with the image here ...
image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg"));
jLabel1.setIcon(new ImageIcon(image));
}
catch (IOException e)
{
// log the exception
// re-throw if desired
}
I'm not sure but try this...
try
{
JLabel picture=new JLabel();
ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg")));
picture.setIcon(ic);
}
catch(Exception)
{
}

Categories

Resources