I have the following code but it seems that something is wrong. I am trying to figure it out but I am stack on it. Any help will be appreciated... thx
/* <applet code="showDemo" height=300 width=300> </applet> */
import java.awt.*;
import java.applet.*;
import java.net.*;
#SuppressWarnings("serial")
public class ShowDemo extends Applet
{
public void start() {
AppletContext ac = getAppletContext();
URL url = getCodeBase();
try{
ac.showDocument(new URL(url + "F:/Work_deepika/JavaVsAndroid.doc"));
}catch(MalformedURLException e){
showStatus("URL not Found ");
}
}
Related
I'm trying to learn how to program frames in Java and I ran into a problem. When I create a jar file of my code I come up with a blank screen. My previous jar files don't have the same problem. When I ran the jar file through command prompt I got the following error message:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at getResources.getImg(getResources.java:31)
at MyCanvas.paint(gameLoop.java:99)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
…
Here is the code for the main class and MyCanvas class:
class MyCanvas extends JComponent{
public void paint(Graphics g){
getResources get = new getResources();
BufferedImage titleImg = get.getImg("Title");
BufferedImage testImg = get.getImage("");
g.drawImage(titleImg, 0, 0, null);
g.drawImage(testImg, 0 , 0, null);
}
}
Here is the code for my "getResources" class:
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.Font;
import sun.audio.AudioData;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
/**
* Write a description of class getResources here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class getResources{
public void getResources(){
}
public BufferedImage getImg(String path){
BufferedImage img = null;
try {
img = ImageIO.read(this.getClass().getResource("/Sprites/" + path + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
public BufferedImage getImage(String path){
BufferedImage img = null;
try {
img = ImageIO.read(this.getClass().getResource("/Sprites/test.png"));
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
public AudioStream getSeven(){
InputStream in;
AudioStream as = null;
try{
in = this.getClass().getResourceAsStream("/Music/seven.wav");
as = new AudioStream (in);
}catch(Exception e){
e.printStackTrace();
}
return as;
}
}
I am pretty sure that the error is in the "getImg" method and the way it retrieves images from the source folder. I removed all the lines of codes that had references to that method and the jar file ran just fine. However, the "getImage" class runs just fine in the jar file. Maybe something about passing a string to get the path of the image creates the error? I'd like to know if anyone knows what is causing the error and if I should even be concerned by not being able to run jar files, I do like using them.
So im importing an image to use as a background and for some reason its giving me:
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(Unknown Source)
at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
Could someone help me?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class PixelLegendsMain extends JFrame implements ActionListener{
public void actionPerformed(ActionEvent e){
}
public static void main(String[ ] args)throws Exception{
PixelLegendsMain plMain = new PixelLegendsMain();
arenaBuild arena = new arenaBuild();
plMain.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
plMain.add(arena);
plMain.setSize(600,460);;
plMain.setVisible(true);
plMain.setResizable(false);
plMain.setLocation(200, 200);
}
}
This is the main class and this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Graphics;
import java.net.URL;
import java.io.*;
import javax.swing.Timer;
public class arenaBuild extends JPanel{
String picPath = "pictures/";
String[] fileName = {picPath+"stageBridge.png", picPath+"turret.png"};
ClassLoader cl = arenaBuild.class.getClassLoader();
URL imgURL[] = new URL[2];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG;
public arenaBuild()throws Exception{
for (int x=0;x<2;x++){
imgURL[x]= cl.getResource(picPath+fileName[x]);
}
imgBG = tk.createImage(imgURL[0]);
}
public void paintComponent(Graphics g){
g.drawImage(imgBG,0,0,600,460,0,0,600,460, this);
}
}
Thjis is where im calling the image in. Im new to this so i'd appreciate if someone can explain why this is happening and help me fix it :D
The most likely explanation is that your tk.createImage(imgURL[0]) call is passing a null URL.
How could this happen? Well the ClassLoader.getResource(String) method is specified as returning null if it can't find a resource ... so it would seem that the problem is that you are using the wrong path for the first resource.
The path you are using appears to be this: "pictures/pictures/stageBridge.png":
It seems unlikely that you really put your images in a directory called "pictures/pictures".
Since you are calling the method on a ClassLoader object (rather than a Class object), the notionally relative path you are using will be treated as an absolute path; i.e. you will get "/pictures/..." rather than "/PixelLegendsMain/pictures/..."
Seems that i unfortuantely did not look at my own code long enough, it seems that i was calling the picPath twice so instead of the path being
"pictures/stageBridge.png"
it was
"pictures/pictures/stageBridge.png"
Sorry for the waste of time, and thank you all for answering
Try printing the current working directory, in order to check if your images path are correct.
This is a simple way of doing that:
System.out.println(new File(".").getAbsolutePath());
Maybe the problem is that the images pictures/tageBridge.png and pictures/turret.png are not the correct path to the file.
Hope it helps!
I'm attempting to display an inline image in a Java JEditorPane. The code below uses HTML content that properly displays the image in Firefox, but not in the JEditorPane. Any ideas why? Thanks.
import javax.swing.*;
import java.awt.*;
public class InlineImage {
public InlineImage() {
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane edit=new JEditorPane();
frame.getContentPane().add(edit);
edit.setContentType("text/html");
String html = "<html><body>Local image<br><img src=\"data:image/png;charset=utf-8;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAyCAYAAACqNX6+AAACeklEQVR42u1bHZBCURgNgiBYCINgIVhYCIKFhSBYCIIgCIKFxSBoZpsJgjAIgmAhCIIgCIKFIAiChSAIF4IgCL7d82abnWl69Xq9+7r1Dhyp93PfOff7ufd+n8/nEyF0AkmgIAQFoSDEjQgSCn1LPD6SbPZDSqWKNBqv0m5nZDh8lsnkUebziIH1OiC/d+wF/tteN50+GPfiGbVaQcrld8nnm8Y78C4K8odAYC3R6Jfkci2pVosGaYtFWDYbvynRKgDx8G4Ij7FgTBjbzQuC2ZhOd4wZCgIOzfBLYysSxooxh8OL2xAEH4KPGo3irs98pwF3CZcXi42vS5CtCPiAaxfBDLPZvRQKNUWW49CDEomBdDrpmxXBDN1uSlKprvj9m8sLgkHAx47HMU+JYObSkBmenxDYvDGTaRum63UhdoFUG9maa4IgW4KZkvzD6PVebMaYEy6GSS6XdyTcIlaroA1rsRgr6vU3zwVsp4BFZzC4ckYQBCmYH4k9D4NBwmLAP2IZFMNZUY6nxwf+rFRKJNJhYLVvSxAs9Bgz1ADcniQIzIprDLVbL+aua8+PyWSfxCkGOLYsSKuVI2mKAY4tC4LlP0lTv8ViWRAS5g4oyLUKQpelmctiUNcsqDPt1Szt5cJQs4Uht0402zrh5qKGm4tb19XvJ0mkq2ciPKC6ngOq3SNcEms/xXXsCJdFDhoWOeyWAdGFWSsDikTm7hXKwVq4VjEvlLNfWnpmKSkqGFlK+l9Kaj1WuFBs7cWKRrgmbYqtvdyOUCxW9W5HOCQOXBobdtjSxpY2J5o+L0W+55o+7bZFN5t5JW3RT0+fbIsmKAgFISgIBSHU4QdCoO0W7Xd4AwAAAABJRU5ErkJggg==\"></body></html>";
edit.setText(html);
frame.setSize(500,300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {new InlineImage();}
}
You need to add a protocol handler for "data:" so an URL/URLConnection can be opened for it. Alternatively you could create some protocol handler "resource:" for class path resources.
You need a package data with a class Handler (fixed name convention!). This will be the factory class for "data:" return an URLConnection. We will create DataConnection for that.
Installing a protocol handler can be done via System.setProperty. Here I provided Handler.install(); to do that in a generic way.
package test1.data;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class Handler extends URLStreamHandler {
#Override
protected URLConnection openConnection(URL u) throws IOException {
return new DataConnection(u);
}
public static void install() {
String pkgName = Handler.class.getPackage().getName();
String pkg = pkgName.substring(0, pkgName.lastIndexOf('.'));
String protocolHandlers = System.getProperty("java.protocol.handler.pkgs", "");
if (!protocolHandlers.contains(pkg)) {
if (!protocolHandlers.isEmpty()) {
protocolHandlers += "|";
}
protocolHandlers += pkg;
System.setProperty("java.protocol.handler.pkgs", protocolHandlers);
}
}
}
The URLConnection gives an InputStream to the bytes:
package test1.data;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.bind.DatatypeConverter;
public class DataConnection extends URLConnection {
public DataConnection(URL u) {
super(u);
}
#Override
public void connect() throws IOException {
connected = true;
}
#Override
public InputStream getInputStream() throws IOException {
String data = url.toString();
data = data.replaceFirst("^.*;base64,", "");
System.out.println("Data: " + data);
byte[] bytes = DatatypeConverter.parseBase64Binary(data);
return new ByteArrayInputStream(bytes);
}
}
The clever thing here is to use Base64 decoding of DatatypeConverter in standard Java SE.
P.S.
Nowadays one would use Base64.getEncoder().encode(...).
I am trying to pass a selected value from HTML drop-down to an Applet method, using setter method in the Applet. But every time the Javascript is invoked it shows "object doesn't support this property or method" as an exception.
My javascript code :
function showSelected(value){
alert("the value given from"+value);
var diseasename=value;
alert(diseasename);
document.decisiontreeapplet.setDieasename(diseasename);
alert("i am after value set ");
}
My applet code :
package com.vaannila.utility;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import prefuse.util.ui.JPrefuseApplet;
public class dynamicTreeApplet extends JPrefuseApplet {
private static final long serialVersionUID = 1L;
public static int i = 1;
public String dieasenameencode;
//System.out.println("asjdjkhcd"+dieasenameencode);
public void init() {
System.out.println("asjdjkhcd"+dieasenameencode);
System.out.println("the value of i is " + i);
URL url = null;
//String ashu=this.getParameter("dieasenmae");
//System.out.println("the value of the dieases is "+ashu);
//Here dieasesname is important to make the page refresh happen
//String dencode = dieasenameencode.trim();
try {
//String dieasename = URLEncoder.encode(dencode, "UTF-8");
// i want this piece of the code to be called
url = new URL("http://localhost:8080/docRuleToolProtocol/appletRefreshAction.do?dieasename="+dieasenameencode);
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
InputStream ois = con.getInputStream();
this.setContentPane(dynamicView.demo(ois, "name"));
ois.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException f) {
f.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
}
++i;
}
public void setDieasename(String message){
System.out.println("atleast i am here and call is made ");
this.dieasenameencode=message;
System.out.println("the final value of the dieasenmae"+dieasenameencode);
}
}
My appletdeployment code :
<applet id="decisiontreeapplet" code="com.vaannila.utility.dynamicTreeApplet.class" archive="./appletjars/dynamictree.jar, ./appletjars/prefuse.jar" width ="1000" height="500" >
</applet>
Change..
document.decisiontreeapplet
..to..
document.getElementById('decisiontreeapplet')
..and it will most likely work.
E.G.
HTML
<html>
<body>
<script type='text/javascript'>
function callApplet() {
msg = document.getElementById('input').value;
applet = document.getElementById('output');
applet.setMessage(msg);
}
</script>
<input id='input' type='text' size=20 onchange='callApplet()'>
<br>
<applet
id='output'
code='CallApplet'
width=120
height=20>
</applet>
</body>
</html>
Java
import javax.swing.*;
public class CallApplet extends JApplet {
JTextField output;
public void init() {
output = new JTextField(20);
add(output);
validate();
}
public void setMessage(String message) {
output.setText(message);
}
}
Please also consider posting a short complete example next time. Note that the number of lines in the two sources shown above, is shorter that your e.g. applet, and it took me longer to prepare the source so I could check my answer.
Try changing the id parameter in your applet tag to name instead.
<applet name="decisiontreeapplet" ...>
</applet>
Try passing parameters using the param tag:
http://download.oracle.com/javase/tutorial/deployment/applet/param.html
I think the <applet> tag is obsolete and <object> tag shoudl be used instead. I recall there was some boolean param named scriptable in the object tag.
Why you do not use deployment toolkit ? It would save you a lot of trying - see http://rostislav-matl.blogspot.com/2011/10/java-applets-building-with-maven.html for more info.
I simply put the class file and the html file in the same directory. And I call the applet with this:
<p align="center">
<applet code="/ShowImage.class" width="200" height="200">
</applet>
</p>
Obviously this doesn't work. What is the most convenient way to setup local development?
edit:
My applet code:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
/**
*
* #author PCKhoi
*/
public class ShowImage extends Applet {
private BufferedImage img;
public void init() {
try {
URL url = new URL(getCodeBase(), "what_I_think.jpg");
img = ImageIO.read(url);
} catch (IOException e) {
}
}
public void paint(Graphics g){
g.drawImage(img,20,20, null);
}
}
Try this
<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET ALIGN="CENTER" CODE="ShowImage.class" WIDTH="800" HEIGHT="500"></APPLET>
</BODY>
</HTML>
and please post your applet code
Some notes:
The code as published (at this instant) does not compile
Do not swallow exceptions in broken code
To compile and run..
prompt> javac ShowImage.java
prompt> appletviewer ShowImage.java
Code (note that the image name will need to be changed back).
//<applet code="ShowImage" width="200" height="200"></applet>
import java.applet.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.net.URL;
/**
* #author PCKhoi
*/
public class ShowImage extends Applet {
private BufferedImage img;
public void init() {
try {
URL url = new URL(getCodeBase(), "icon.png");
img = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g){
g.drawImage(img,20,20, null);
}
}
The important line of the source, in relation to your question, is the first, commented line. It supplies an HTML element that the Applet Viewer will parse and use as a pseudo-HTML.
I think I know why it doesn't load now. The applet was wrapped inside a complex netbeans project, that's why putting the class file and the html file inside the same directory didn't work.
My solution is to use a simple IDE such as DrJava if you don't need project functionality.