showing images on jeditorpane (java swing) - java

I have a JEditorPane created by this way:
JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>");
I put this pane on a JFrame.
Text is shown correctly, but I can't see the picture, there is only a square indicating that there should be an image (i.e.: "broken image" shown by browsers when picture has not been found)

You have to provide type, and get the resource. That's all. My tested example, but I'm not sure about formating. Hope it helps:
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) throws Exception {
Test.createAndShowGUI();
}
private static void createAndShowGUI() throws IOException {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String imgsrc =
Test.class.getClassLoader().getSystemResource("a.jpg").toString();
frame.getContentPane().add(new JEditorPane("text/html",
"<html><img src='"+imgsrc+"' width=200height=200></img>"));
frame.pack();
frame.setVisible(true);
}
}

The JEditorPane is using HTMLDocument.getBase to locate relative urls as well, so if you are displaying content from a directory, make sure to set the base on the html document so it resolves urls relative to the base directory.
Depending on where that image actually is, you might want to extend HTMLEditorKit+HTMLFactory+ImageView and provide a custom implementation of ImageView, which is responsible for mapping the attribute URL to the image URL, too.

None of the above worked for me, however 'imgsrc = new File("passport.jpg").toURL().toExternalForm();' let me to try and have each image in the html have a preceding 'file:' so that it now reads:
<img src="file:passport.jpg" />
And that works fine for me.

If you want to specify relative path to the image.
Let's say your project folder structure is as following:
sample_project/images
sample_project/images/loading.gif
sample_project/src
sampler_project/src/package_name
Now the image tag would look like this:
"<img src='file:images/loading.gif' width='100' height='100'>"
Yaay!

I used this when I was working in netbeans, it worked though. I think a little modification if the program should run outside of netbeans,
String imgsrc="";
try {
imgsrc = new File("passport.jpg").toURL().toExternalForm();
} catch (MalformedURLException ex) {
Logger.getLogger(EntityManager.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println(imgsrc); use this to check
html = "<img src='" + imgsrc + "' alt='' name='passport' width='74' height='85' /><br />";
//use the html ...
if you run from the jar, the image file has to be on the same directory level, ...
in fact, the image file has to be on the same directory as your execution entry.

Related

How to display uploaded image via CSS

i want to upload an image via primefaces:fileUpload and then display it on a div for example with css.
I can already save the image on the server:
public void upload() throws IOException, URISyntaxException {
if (logo != null) {
File fileImage = new File(System.getProperty("jboss.server.data.dir"), "uploads.png");
BufferedImage img = ImageIO.read(new ByteArrayInputStream(logo.getContents()));
if (fileImage.exists()) {
fileImage.delete();
}
ImageIO.write(img, "png", fileImage);
}
}
And then i tried to get the web path to the file but that didn't worked:
public String getImagePath(){
File fileImage = new File(System.getProperty("jboss.server.data.dir"), "uploads.png");
Set<String> set = FacesContext.getCurrentInstance().getExternalContext().getResourcePaths(fileImage.getAbsolutePath());
return set.iterator().next();
}
I need something like this:
/ewarehouse/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&v=6.2&v=6.2&pfdrid=f52e395e4f38c09a1990e8f9d0c5806d&pfdrt=sc&pfdrid_c=true
Can someone help me or has a other way to do this ?
It worked for me to create a servlet and refered to the file position.
background-image: url('#{'/'}ewarehouse#{'/'}images//dynamic#{'/'}?file=uploads.png')
In css it look a bit weird but this way it worked Thanks for the answer to #JasperdeVries and #Kukeltje

Load Image into JLabel not working

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

Java: opening a resource (txt file) which is in a jar with OS standard application

i get the error "AWT-EventQueue-0 java.lang.IllegalArgumentException: URI is not hierarchical".
-I'm trying to use the java.awt.Desktop api to open a text file with the OS's default application.
-The application i'm running is launched from the autorunning jar.
I understand that getting a "file from a file" is not the correct way and that it's called resource. I still can't open it and can't figure out how to do this.
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Is there a way to open the resource with the standard os application from my application?
Thx :)
You'd have to extract the file from the Jar to the temp folder and open that temporary file, much like you would do with files in a Zip-file (which a Jar basically is).
You do not have to extract file to /tmp folder. You can read it directly using `getClass().getResourceAsStream()'. But note that path depend on where your txt file is and what's your class' package. If your txt file is packaged in root of jar use '"/prova.txt"'. (pay attention on leading slash).
I don't think you can open it with external applications. As far as i know, all installers extract their compressed content to a temp location and delete them afterwards.
But you can do it inside your Java code with Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
Wrong
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Right
/**
Do you accept the License Agreement of XYZ app.?
*/
import java.awt.Dimension;
import javax.swing.*;
import java.net.URL;
import java.io.File;
import java.io.IOException;
class ShowThyself {
public static void main(String[] args) throws Exception {
// get an URL to a document..
File file = new File("ShowThyself.java");
final URL url = file.toURI().toURL();
// ..then do this
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JEditorPane license = new JEditorPane();
try {
license.setPage(url);
JScrollPane licenseScroll = new JScrollPane(license);
licenseScroll.setPreferredSize(new Dimension(305,90));
int result = JOptionPane.showConfirmDialog(
null,
licenseScroll,
"EULA",
JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
System.out.println("Install!");
} else {
System.out.println("Maybe later..");
}
} catch(IOException ioe) {
JOptionPane.showMessageDialog(
null,
"Could not read license!");
}
}
});
}
}
There is JarFile and JarEntry classes from JDK. This allows to load a file from JarFile.
JarFile jarFile = new JarFile("jar_file_Name");
JarEntry entry = jarFile.getJarEntry("resource_file_Name_inside_jar");
InputStream stream = jarFile.getInputStream(entry); // this input stream can be used for specific need
If what you're passing to can accept a java.net.URLthis will work:
this.getClass().getResource("prova.txt")).toURI().toURL()

Debug SplashScreen from Eclipse without generating the Jar

I have search all over the web but could not find answer to this question:
I need to debug the functioning of an application that changes the SplashScreen based on the module you are accessing.
I do know that the code:
SplashScreen splash = SplashScreen.getSplashScreen();
Can be used to get the instance when you pass either:
Splash from command line: java -splash:path/image.gif ClassFile
Splash image in manifest: splashscreen-image: img/SplashNomina.gif
Still when I tried to run the application by passing the -splash value from VM args in Eclipse it did not work.
Is it actually possible as SplashScreen.getSplashScreen() is always NULL.
I have been trying passing without success:
-splash:image.gif
-Dsplash=image.gif
Right now I see lots of limitations in this Splash api, as it is always required to have a parameter being passed. I think it would be much more flexible to be able to just pass the parameter at runtime :(
Any help woult be really appreciated!
OK, this has bitten me too.
I built a runnable jar
with manifest entry
SplashScreen-Image: MyGraphic.jpg
and it works as it's supposed to.
From Eclipse, specifying the VM arg as
-splash:MyGraphic.jpg
no such luck
SplashScreen.getSplashScreen() returns null.
The reason for this is the brain-dead implementation of SplashScreen.getSplashScreen() in the JDK (at least 1.6). I think. It's kind of hard to tell without getting into what the native code is doing. But, here is this method from java.awt.SplashScreen. I'm not sure if it's called but studying it did provide me with the essential clue I needed to get this working in Eclipse:
public synchronized URL getImageURL() throws IllegalStateException {
checkVisible();
if (imageURL == null) {
try {
String fileName = _getImageFileName(splashPtr);
String jarName = _getImageJarName(splashPtr);
if (fileName != null) {
if (jarName != null) {
imageURL = new URL("jar:"+(new File(jarName).toURL().toString())+"!/"+fileName);
} else {
imageURL = new File(fileName).toURL();
}
}
}
catch(java.net.MalformedURLException e) {
// we'll just return null in this case
}
}
return imageURL;
}
Note that in the case of a file (i.e. command-line rather than jar launch) it's not doing a getResource() to get the URL but opening a file relative to the CWD. Since Eclipse run configurations default to running from the root of the project, the answer is to specify the path as a relative path and not to expect a classpath lookup.
Therefore, since I am building with maven, my image is located at src/main/resources/MyGraphic.jpg. Specifying this as the command line parameter: i.e.
-splash:src/main/resources/MyGraphic.jpg
allows it to work in Eclipse (or, I guess, any command line)
I'm not sure WHY this is, since the getImageURL method is NOT called by getSplashScreen() but it DOES work.
To me this is kind of brain-dead on the part of Sun/Oracle. They could have easily done a classpath lookup with something like
imageURL = getResource(filename) but they did not.
The short answer is that the Splash Screen command line syntax refers to a filename relative to the current working direrctory, not relative to the classpath.
I'm answering 3 years later but I had the same problem and I tried to resolve.
I found the solution, and I think it would be useful to everybody.
You have to create a launch configuration, specifying in the VM arguments the parameter -splash:image.gif. This parameter refers to the root directory of the project (not /bin or /src). So you have to put your image in the same level as /bin and /src (or you can specify a different path in the -splash option).
When you export the runnable JAR from 'export' specifying the launch configuration you created before, it says 'can't include VM arguments, you have to specify from command line' (and it doesn't include your image.gif in the root).
So if you want to have a runnable jar with your splash image, you can refer to another topic on stackoverflow which i'm not finding anymore. Someone answered that the best solution is FatJar. You can proceed as follows: export > other > fat jar exporter. Tick 'select manifest file', specifying a MANIFEST.MF containing 'SplashScreen-Image: splash.gif' (if you don't know how to create, deselect this checkbox, create a jar with the default one, modify the one created and include it). In the next page of the exportation, be sure to include your images in the jar with the 'add dir' button (it includes the content of the directory specified to the root directory of the project, so pay attention with the directory in the manifest).
It worked for me.
So if you want to run with eclipse, add the splash image to the root directory and specify -splash:image.gif in the VM arguments. If you want to export a JAR, the FatJar plugin worked for me as I specified.
I hope it helps :)
(sorry for my english, i'm not english :P)
Well guys, I decided yo go my independent way because the Splash class is too monolithic, so here I put my class:
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SplashWindow extends JFrame {
private static final long serialVersionUID = 9090438525613758648L;
private static SplashWindow instance;
private boolean paintCalled = false;
private Image image;
private SplashWindow(Image image) {
super();
this.image = image;
JLabel label = new JLabel();
label.setIcon(new ImageIcon(image));
this.add(label);
this.setUndecorated(true);
this.setAlwaysOnTop(true);
this.pack();
this.setLocationRelativeTo(null);
}
public static void splash(URL imageURL) {
if (imageURL != null) {
splash(Toolkit.getDefaultToolkit().createImage(imageURL));
}
}
public static void splash(Image image) {
if (instance == null && image != null) {
instance = new SplashWindow(image);
instance.setVisible(true);
if (!EventQueue.isDispatchThread() && Runtime.getRuntime().availableProcessors() == 1) {
synchronized (instance) {
while (!instance.paintCalled) {
try {
instance.wait();
} catch (InterruptedException e) {
}
}
}
}
}
}
#Override
public void update(Graphics g) {
paint(g);
}
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
if (!paintCalled) {
paintCalled = true;
synchronized (this) {
notifyAll();
}
}
}
public static void disposeSplash() {
instance.setVisible(false);
instance.dispose();
}
}
Hope it helps someone ;)

How do I change the default application icon in Java?

I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.
Here's what I have at the moment (leaving out the try-catch block):
URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);
The class that contains this code is in the com.xyz package, if that makes any difference. That class also extends JFrame. This code is throwing a MalformedUrlException on the first line.
Anyone have a solution that works?
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
May or may not require a '/' at the front of the path.
You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:
Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))
Do not forget to import:
import java.awt.Toolkit;
in the source code!
Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.
com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.
Try This write after
initcomponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));
/** Creates new form Java Program1*/
public Java Program1()
Image im = null;
try {
im = ImageIO.read(getClass().getResource("/image location"));
} catch (IOException ex) {
Logger.getLogger(chat.class.getName()).log(Level.SEVERE, null, ex);
}
setIconImage(im);
This is what I used in the GUI in netbeans and it worked perfectly
In a class that extends a javax.swing.JFrame use method setIconImage.
this.setIconImage(new ImageIcon(getClass().getResource("/resource/icon.png")).getImage());
You should define icons of various size, Windows and Linux distros like Ubuntu use different icons in Taskbar and Alt-Tab.
public static final URL ICON16 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug16.png");
public static final URL ICON32 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug32.png");
public static final URL ICON96 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug96.png");
List<Image> images = new ArrayList<>();
try {
images.add(ImageIO.read(HelperUi.ICON96));
images.add(ImageIO.read(HelperUi.ICON32));
images.add(ImageIO.read(HelperUi.ICON16));
} catch (IOException e) {
LOGGER.error(e, e);
}
// Define a small and large app icon
this.setIconImages(images);
You can try this one, it works just fine :
` ImageIcon icon = new ImageIcon(".//Ressources//User_50.png");
this.setIconImage(icon.getImage());`
inside frame constructor
try{
setIconImage(ImageIO.read(new File("./images/icon.png")));
}
catch (Exception ex){
//do something
}
Example:
URL imageURL = this.getClass().getClassLoader().getResource("Gui/icon/report-go-icon.png");
ImageIcon iChing = new ImageIcon("C:\\Users\\RrezartP\\Documents\\NetBeansProjects\\Inventari\\src\\Gui\\icon\\report-go-icon.png");
btnReport.setIcon(iChing);
System.out.println(imageURL);

Categories

Resources