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);
Related
Apparently, this is my code I have been using to get image from my disks to my program.
public void getVehicleImage(){
FileDialog fd = new FileDialog(this);
fd.setFile("*.jpg; *.jpg; *.png; *.gif");
fd.show();
vehicle_path = fd.getDirectory()+fd.getFile();
vehicleFileName.setText(vehicle_path = fd.getFile());
vehicleImagePath.setText(vehicle_path = fd.getDirectory()+fd.getFile());
image.setIcon(new ImageIcon(vehicle_path));
}
How do I fit the image to the size of my jLabel? I have tried using the
getScaledInstance()
but still no good. And also I want to ask if I am using the right code on how to get Image from my disk? I kinda feel it is wrong.
I faced similar problem and did below workaround:
Step1: Read the picture as a BufferedImage from your file system.
BufferedImage image = null;
try {
image = ImageIO.read(new File("fileName.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Step2: Create a new BufferedImage that is the size of the JLabel
BufferedImage img= image.getScaledInstance(label.width, label.height,
Image.SCALE_SMOOTH);
Step3: Create new ImageIcon from the resized BufferedImage (Step 2)
ImageIcon imageIcon = new ImageIcon(img);
In your case, create a helper method and call it while creating ImageIcon as below:
public void getVehicleImage(){
...................
image.setIcon(new ImageIcon(getScaledImage(vehicle_path)));//call helper here
}
This can be helper function:
public BufferedImage getScaledImage(String imagePath){
BufferedImage image = null;
try {
image = ImageIO.read(new File("fileName.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
BufferedImage img= image.getScaledInstance(label.width, label.height,
Image.SCALE_SMOOTH);
return img;
}
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.
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.
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.
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)
{
}