I have coded a program in Eclipse and it works properly when I run in that.
public static void initialize() throws IOException{
JTextField tfQrText;
int size = 250;
File qrFile;
BufferedImage qrBufferedImage;
JFrame gui = new JFrame("qrCode Generator");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(250, 340);
gui.setLayout(new BorderLayout());
gui.setResizable(false);
File iconFile = new File(VisualQrCodeGenerator.class.getResource("icon.png").getFile());
BufferedImage iconBuffered = ImageIO.read(iconFile);
gui.setIconImage(iconBuffered);
JButton generate = new JButton("Generate qrCode");
gui.add(generate,BorderLayout.SOUTH);
tfQrText = new JTextField();
PromptSupport.setPrompt("Enter Your Text ... ", tfQrText);
gui.add(tfQrText,BorderLayout.NORTH);
qrFile = new File(VisualQrCodeGenerator.class.getResource("qrCodeImage.png").getFile());
qrBufferedImage = ImageIO.read(qrFile);
ImageIcon qrImageIcon = new ImageIcon(qrBufferedImage);
JLabel image = new JLabel();
image.setIcon(qrImageIcon);
image.setHorizontalAlignment(JLabel.CENTER);
gui.add(image,BorderLayout.CENTER);
gui.setVisible(true);
generate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(!(tfQrText.getText().equals(""))){
//create() Method make the QRcode Image
create();
}
}
});
The Error occurs on line:
BufferedImage iconBuffered = ImageIO.read(iconFile);
When I make it .jar file, it says:
My Project structure is like this:
+src
+qrCodeGenerator
-VisualQrCodeGenerator
-icon.png
-qrCodeImage.png
The code is running properly and without any error in program and I can work with it. But when I make it .jar file, it errors me as I uploaded it image.
This is normal: you can't access a classpath resource as a File object. This is because it is embedded inside a JAR. It works inside your IDE because resources are typically stored inside a temporary folder (and not inside a JAR).
You need to access it with an InputStream using Class.getResourceAsStream and use ImageIO.read(InputStream) instead.
As such, change your code to:
qrBufferedImage = ImageIO.read(VisualQrCodeGenerator.class.getResourceAsStream("qrCodeImage.png"));
and
iconBuffered = ImageIO.read(VisualQrCodeGenerator.class.getResourceAsStream("icon.png"));
Related
Ok, I am not sure what I am doing wrong here but I am not able to reference images in my NB Java project. My code is basically the same as this:
ImageIcon i = new ImageIcon("Resources/character.png");
I Have a package called Resources in my src, and character.png in that package, so what am I doing wrong?
If your file is within the class path (eg. <project>/src/Resources/character.png), load it as resource:
Here's an example:
public class Example
{
public ImageIcon loadImage()
{
// Note the '/'
final String path = "/Resources/character.png";
// Load the image as a resource
ImageIcon icon = new ImageIcon(this.getClass().getResource(path));
// Return the result
return icon;
}
}
// ...
Example e = new Example();
ImageIcon icon = e.loadImage();
I know what the problem is I just do not know how to fix it. So I have an image that I am trying to render in my program. I use ImageIO to load the image. But it seems to have a problem wit the path I am giving it. I am using NetBeans as my IDE and I dont know if I am saving the image file correctly.
First method:
public void init(){
BufferedImageLoader loader = new BufferedImageLoader();
try{
spriteSheet = loader.loadImage("/sprite_sheet.png");
}catch(IOException e){
e.printStackTrace();
}
SpriteSheet ss = new SpriteSheet(spriteSheet);
player = ss.grabImage(1,1,32,32);
}
the loader BufferedImageLoader class:
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path) throws IOException{
image = ImageIO.read(getClass().getResource(path));
return image;
}
}
I have the image saved under a 'res' folder under 'src' folder.
Error:
Exception in thread "Thread-2" java.lang.IllegalArgumentException: input == null!
Thank you.
Why do you need to use getClass().getResource() ?
Most simple usage of ImageIO.read is as follows.
image = ImageIO.read(new File(path));
You may need to add folders to path also.
spriteSheet = loader.loadImage("/src/res/sprite_sheet.png");
Try using an absolute path for your file or if you need a relative check this post (eg assuming you have a res folder under default package did you try "/res/yourfile"
I try to display an image using a JLabel. This is my project navigator:
From SettingsDialog.java I want to display an image using following code:
String path = "/images/sidebar-icon-48.png";
File file = new File(path);
Image image;
try {
image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
header.add(label); // header is a JPanel
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The code throws an exception: Can't read input file!
Is the path of the image is wrong?
Don't read from a file, read from the class path
image = ImageIO.read(getClass().getResource(path));
-or-
image = ImageIO.read(MyClass.class.getResource(path));
When you use a File object, you're telling the program to read from the file system, which will make your path invalid. The path you are using is correct though, when reading from the class path, as you should be doing.
See the wiki on embedded resource. Also see getResource()
UPDATE Test Run
package org.apache.openoffice.sidebar;
import javax.swing.*;
public class SomeClass {
public SomeClass() {
ImageIcon icon = new ImageIcon(
SomeClass.class.getResource("/images/sidebar-icon-48.png"));
JLabel label = new JLabel(icon);
JFrame frame = new JFrame("Test");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SomeClass();
}
});
}
}
"/images/sidebar-icon-48.png" is root path. On windows would be c:\images\sidebar-icon-48.png or d:\images\sidebar-icon-48.png depending on current drive (java converts the / to \ - not an issue). Linux images would a child of root /images/sidebar-icon-48.png Need to load relative to class or relative to the jar that had the class (if you do not want to store images inside jar.
In big projects its nice to have images and other resources outside the jar so the jar is smaller and more importantly its easy to change the resources without fiddling with jars/ wars.
Since you seem to be making a add on for open office, you will have to keep everything in jar and so peeskillet answer is right. But make sure your images folder is being packed in the jar. Extract the jar ising the jar command or rename the file to zip and extract.
Or check and fix project settings. How to make a jar in eclipse ... latest one has a wizard that makes an ant script or this SO
try to use this directly :
JLabel label = new JLabel(new ImageIcon(path));
and delete these line :
File file = new File(path);
image = ImageIO.read(file);
if error still exist paste the following error
I want to open New MS Word Document to open on button click in java
can you suggest me the code , I am doing this by following code but i think its to open the existing document not to create the new document
class OpenWordFile {
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /C start Employee.doc");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Exception occured" + ex);
}
}
}
You can not do this using Java alone, at least if you need to generate DOC Files you need a 3rd tool library Aspose for example. Take a look at this thread, otherwise you can open existing files using the runtime.
only the comment with out any words
Runtime run = Runtime.getRuntime();
String lcOSName = System.getProperty("os.name").toLowerCase();
boolean MAC_OS_X = lcOSName.startsWith("mac os x");
if (MAC_OS_X) {
run.exec("open " + file);
} else {
//run.exec("cmd.exe /c start " + file); //win NT, win2000
run.exec("rundll32 url.dll, FileProtocolHandler " + path);
}
In the recent release (Java 6.0), Java provides Desktop class. The purpose of the class is to open the application in your system that is associated with the given file. So, if you invoke open() method with a Word document (.doc) then it automatically invokes MS Word as that is the application associated with .doc files.
I have developed a small Swing program (though you can develop it as a console application) to take document number from user and invoke document into MSWord. The assumption is; documents are stored with filename consisting of <document number>>.doc.
Given below is the Java program that you can compile and run it as-it-is. Make sure you change DIR variable to the folder where .doc files are stored.
Here is the code to open Word Doc in Java... its an extract from net....
import java.io.File;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class WordDocument extends JFrame {
private JButton btnOpen;
private JLabel jLabel1;
private JTextField txtDocNumber;
private static String DIR ="c:\\worddocuments\\"; // folder where word documents are present.
public WordDocument() {
super("Open Word Document");
initComponents();
}
private void initComponents() {
jLabel1 = new JLabel();
txtDocNumber = new JTextField();
btnOpen = new JButton();
Container c = getContentPane();
c.setLayout(new java.awt.FlowLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Enter Document Number : ");
c.add(jLabel1);
txtDocNumber.setColumns(5);
c.add(txtDocNumber);
btnOpen.setText("Open Document");
btnOpen.addActionListener(new ActionListener() { // anonymous inner class
public void actionPerformed(ActionEvent evt) {
Desktop desktop = Desktop.getDesktop();
try {
File f = new File( DIR + txtDocNumber.getText() + ".doc");
desktop.open(f); // opens application (MSWord) associated with .doc file
}
catch(Exception ex) {
// WordDocument.this is to refer to outer class's instance from inner class
JOptionPane.showMessageDialog(WordDocument.this,ex.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
}
}
});
c.add(btnOpen);
} // initCompnents()
public static void main(String args[]) {
WordDocument wd = new WordDocument();
wd.setSize(300,100);
wd.setVisible(true);
}
}
Maybe using java.awt.Desktop can help?
File f = new File("<some temp path>\\file.docx");
f.createNewFile();
Desktop.getDesktop().open(f);
Creates a new empty document and opens it with the systsem specifik program for the extension. The strength of this solution is that it works for all OS... As long as the OS has a program to view the file that is.
Although I suspect that you are looking for semthing with abit more control over the creation of the file...
Out-of-the-box ArrayIndexOutOfBoundsException when attempting to use Apache-Commons Sanselan to load a TIFF that was compressed with PackBits compression.
Code:
import org.apache.sanselan.*;
public class TIFFHandler {
public static Image loadTIFF(String fileName) throws ImageReadException, IOException {
File imageFile = new File(fileName);
BufferedImage bi = Sanselan.getBufferedImage(imageFile);
return bi;
}
public static void main(String[] args) throws IOException, ImageReadException {
String TIFFFILE = "test_image.tif";
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
BufferedImage bi = (BufferedImage) loadTIFF(TIFFFILE);
ImageIcon ii = new ImageIcon(bi);
JLabel lbl = new JLabel(ii);
panel.add(lbl);
frame.setVisible(true);
}
}
Stack trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 426
at org.apache.sanselan.common.PackBits.decompress(PackBits.java:55)
at org.apache.sanselan.formats.tiff.datareaders.DataReader.decompress(DataReader.java:127)
at org.apache.sanselan.formats.tiff.datareaders.DataReaderStrips.readImageData(DataReaderStrips.java:96)
at org.apache.sanselan.formats.tiff.TiffImageParser.getBufferedImage(TiffImageParser.java:505)
at org.apache.sanselan.formats.tiff.TiffDirectory.getTiffImage(TiffDirectory.java:163)
at org.apache.sanselan.formats.tiff.TiffImageParser.getBufferedImage(TiffImageParser.java:441)
at org.apache.sanselan.Sanselan.getBufferedImage(Sanselan.java:1264)
at org.apache.sanselan.Sanselan.getBufferedImage(Sanselan.java:1255)
at TIFFHandler.loadTIFF(FieldSheetHandler.java:42)
at TIFFHandler.main(FieldSheetHandler.java:90)
I've attempted an analysis of the problem, but I'm pretty lost...any directions would be really helpful. TIFF images are a pain in the a**.
You can try the updated version of Commons Imaging from the Apache snapshot repository. The Javadoc is not online yet, you'll have to build it by checking out the code from SVN and running mvn javadoc:javadoc.
If you find more issues or want to suggest an improvement you can file them in JIRA. Also the developers will be happy to help you if you have questions regarding the usage of the API. They await you on the mailing list.