Hot questions for Using Applets in class

Question:

I am attempting to generate a CAP file and an export file from the Wallet.java which comes standard in the Java Card SDK under the samples directory. I compile the class, use the converter and encounter the following:

$ javac -g -d classes/ src/com/sun/javacard/samples/wallet/Wallet.java
$ converter -debug -verbose -classdir "$JC_HOME/samples/src" com.sun.javacard.samples.wallet 0xa0:0x0:0x0:0x0:0x62:0x3:0x1:0xc:0x6:0x1 1.0

Java Card 2.2.2 Class File Converter, Version 1.3
Copyright 2005 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms.

parsing /home/user/javacard/java_card_kit-2_2_2/samples/src/com/sun/javacard/samples/wallet/Wallet.class
error: com.sun.javacard.samples.wallet.Wallet: unsupported class file format of version 50.0.

conversion completed with 1 errors and 0 warnings.

My Java version and javac versions are the same, Java 1.6:

$ java -version
java version "1.6.0_45"
Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode)
$ javac -version
javac 1.6.0_45

I am using JC SDK 2.2.2 on Ubuntu 14.04. The version of the converter is 1.3:

$ converter -version
Java Card 2.2.2 Class File Converter, Version 1.3
Copyright 2005 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms.

I cannot seem to resolve this "unsupported class file format of version 50.0" error. I am slightly puzzled as to why I am encountering this error given Java 1.6 is version 50.0.

Has anyone else encountered the same issue?


Answer:

The Java Card 2.2.2 converter supports at most the Java 5 class file format (hence it tells you that Java 6/version 50.0 is not supported). Thus, you need to specify the source compatibility/class file version when compiling the source code using newer JDK versions:

javac -g -source 1.5 -target 1.5 -d classes/ src/com/sun/javacard/samples/wallet/Wallet.java

Similarly, for Java Card 2.2.1, you would use version 1.2:

javac -g -source 1.2 -target 1.2 -d classes/ src/com/sun/javacard/samples/wallet/Wallet.java

And for Java Card 2.1.1 (JC SDK 2.1.2), you would use version 1.1:

javac -g -source 1.1 -target 1.1 -d classes/ src/com/sun/javacard/samples/wallet/Wallet.java

You can check the version of a class file with the Java class file disassembler (thanks to @cmanning for mentioning this):

javap -v -cp classes/ com.sun.javacard.samples.wallet.Wallet |grep 'version'

Question:

I get the ClassNotFoundException error when I make my html file with the code and jar file. Not sure why. Here's what I have:

 <html>
<head>
<title>
Test Applet
</title>
</head>
<body>
<h2>Test Applet</h2>
<applet
code="Testing.class"
archive="myTestJar.jar" 
width=550 height=300>
</applet>
</body>
</html>

I simply have the class in a jar file and tried to reference using archive but it doesn't work.


Answer:

try this

<applet code=Testing.class
        archive="myTestJar.jar"
        width=550 height=300>
</applet>

The class has your main() I assume, the jar is the entire thing.

if,you're not taking packages into consideration. For instance, if the package is myPackage.vol3 then the line should read

<applet code="myPackage.vol3.Testing.class" archive="myTestJar.jar"

and put the html file in the project folded "INSIDE" the project folder.

Question:

I know nothing about Java at all and I only need to run an applet on browser in localhost.

I only download the .class file from the following website

http://isgwww.cs.uni-magdeburg.de/tspanner/TSpanner.html

and I need to run this .class file on my localhost.

I tried every solution given in Java applet Error … What is wrong? but I failed to run it.

This is my HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head>
 <title>Visualization of Spanners - The Applet</title>
</head>
<body alink="#990099" bgcolor="#cccccc" link="#000099" vlink="#000099">
<applet code="gsn.TSpanner" align="BOTTOM" height="480" width="720"></applet>
</body></html>

In the directory where this .html is placed, I created a folder and renamed it to gsn and copied TSpanner.class file in there, after going to the url of the .html file Java throws the following error

NoClassDefFoundError

gsn/TSpanner (wrond name:TSpanner)

I also tried copying .class file in the root directory and setting

<applet code="TSpanner.class" align="BOTTOM" height="480" width="720"></applet>

It didn't work again.

Is it possible to run this .class in localhost? There is no more files (like .jar) and if yes how?

Thanks.


Answer:

I was able to get this applet to run using the appletviewer command line tool which comes with the JDK. The appletviewer tool expects you to feed it an HTML page containing an <applet> tag, so I created the following mock page for this purpose:

<HTML>
    <HEAD><TITLE>Test Page</TITLE></HEAD>
    <BODY>
    <APPLET code="TSpanner.class" align="BOTTOM" height="480" width="720"></applet>
    </BODY>
</HTML>

Save this HTML page in a directory somewhere and call it test.html. You will be using this later with the appletviewer tool.

The trick to getting it to run was to download all the class files upon which TSpanner.class is dependent. This meant downloading the following 5 class files:

  • TSpanner$AnimateThread.class
  • Path.class
  • Sheet.class
  • Point.class
  • PointVector.class

I downloaded these files from my browser by typing in the URL which Java itself would use, running from your browser, to obtain the necessary files. Here is a sample URL which I used to download the Point.class file:

http://isgwww.cs.uni-magdeburg.de/tspanner/Point.class

Do this for each of the five required class files (by simply changing the name of the class file at the end of the above URL), and save them into a directory at the same level as the test.html page which you created above.

Finally, you can run the Java appletviewer from the command line. Change directories to the bin directory of your Java installation and then run the following:

C:\Program Files\Java\jdk1.7.0_80\bin\appletviewer.exe test.html

Once it launches, you will see the applet running in its own window. Here is a screen capture of what it looked like running on my own machine:

You could try to get this applet to run in your Firefox browser, but unless you plan on putting this in your own webpage, appletviewer is probably the easier way to go. As you probably figured out, most browsers are dropping support for the <applet> tag at this point.

Question:

So, I have one class, with a radio button set up in it. Then in a second class, I extended the first class and made 3 "if" statements that will create an applet depending on the output of the radio button. In those "if" statements, it says that the variables cannot be resolved. How do I get these resolved? And please tell me if there are there any other errors in my code. Thanks a million, :D.

Thanks, any help will help greatly.

//  The First Class Code:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class RadioButton extends JPanel {

    static JFrame frame;

   JLabel pic;
   RadioListener myListener = null;
   public RadioButton() {



       // Create the radio buttons
       JRadioButton displacement = new JRadioButton("Displacement");
       displacement.setMnemonic(KeyEvent.VK_N);
       displacement.setSelected(true);
        //Displacement Button, set to automatically be clicked

       JRadioButton accel = new JRadioButton("Acceleration");
       accel.setMnemonic(KeyEvent.VK_A);
       accel.setActionCommand("acceleration");
        //Acceleration Button

       JRadioButton time = new JRadioButton("Change in time");
       time.setMnemonic(KeyEvent.VK_S);
       time.setActionCommand("deltaT");
        //The change in time button


       // Creates the group of buttons
       ButtonGroup group = new ButtonGroup();
       group.add(displacement);
       group.add(accel);
       group.add(time);

              myListener = new RadioListener();
                displacement.addActionListener(myListener);
                accel.addActionListener(myListener);
                time.addActionListener(myListener);


      // Set up the picture label
       pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg"));          //Set the Default Image

       pic.setPreferredSize(new Dimension(177, 122)); 


       // Puts the radio buttons down
       JPanel panel = new JPanel();
       panel.setLayout(new GridLayout(0, 1));
       panel.add(displacement);
       panel.add(accel);
       panel.add(time);


       setLayout(new BorderLayout());
       add(panel, BorderLayout.WEST);
       add(pic, BorderLayout.CENTER);
       setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
   } 



   //Listening to the buttons
   class RadioListener implements ActionListener { 
       public void actionPerformed(ActionEvent e) {
           pic.setIcon(new ImageIcon(""+e.getActionCommand() 
                                         + ".jpg"));
       }
   }

   public static void main(String s[]) {
        frame = new JFrame("∆x = Vavg * time");
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });

        frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
   }
} 

My second class, with the if statements

    import java.lang.Object;
    import java.awt.Graphics;


    public class RadioButtonMain extends RadioButton {

        public static void main(String [ ] args) {
        if ( displacement.isSelected())
          {
    //Option 1 for applet
          }

        if ( accel.isSelected()) {
            //Option 2 for applet
        }

        else {
            //Option 3 for applet
        }
        }
    }

Answer:

displacement is a local variable in your constructor. Therefore it won't be accessible outside the constructor.

If you want it to be accessible to other methods in the class, move it out of the constructor and make it an instance field, by saying JRadioButton displacement; above the constructor, in the same place where you declare myListener. In fact, you've already done the right thing with myListener, so you need to do the same thing with displacement.

This will make displacement accessible to other methods in the RadioButton class, but not to subclasses like RadioButtonMain. To make it accessible to RadioButtonMain, make the field protected:

protected JRadioButton displacement;

or, probably better, make it private and add a getter method to RadioButton to return the field, since you probably don't want subclasses to change displacement any time they feel like it.

Also, make sure you change this in your constructor:

JRadioButton displacement = new JRadioButton("Displacement");

to this:

displacement = new JRadioButton("Displacement");

so that you don't have a local variable with the same name as the field.

Finally, note that the main method is static. So even though it's defined inside RadioButtonMain, it won't have access to any fields of RadioButtonMain, including displacement. Make it something like this:

 public static void main(String [ ] args) {
     new RadioButtonMain().doMain();
 }

 public void doMain() {
    if ( displacement.isSelected())
      {
//Option 1 for applet
      }

    if ( accel.isSelected()) {
        //Option 2 for applet
    }

    else {
        //Option 3 for applet
    }
    }
}

This gives you a RadioButtonMain (which is also a RadioButton) to work with. Note that the RadioButton constructor will be called before doMain is called, which is what you want because the constructor sets up displacement.

Question:

I need to run separate process from Java applet. I want to use class, which lie inside jar:

myApplet.jar
 - packagename.MainApplet.class
 - packagename.ProcToRun.class

File MainApplet has interface Applet implementation and from inside of this code I'd like to run ProcToRun class as separete process. ProcToRun has main method.

I've tried code like this:

Process p = new ProcessBuilder("java", "-cp", ".;./myApplet.jar", ProcToRun.class.getName()).start();

and similar (Runtime.exec(command), different notation - \\, / or with full url), but I got:

Error: Could not find or load main class packagename.ProcToRun

Java.exe is visible, applet is signed - have all permissions, using win 8.1, java 8 u 25. I think there is something wrong with classpath, but I can't find the solution.


Answer:

The Java command cannot use URLs for the Jar to run, so it would be necessary to download the Jar explicitly to the local file system before attempting to run it.

But on seeing a Process, two tips:

  1. See When Runtime.exec() won't for many good tips on creating and handling a process correctly. Then ignore it refers to exec and use a ProcessBuilder to create the process.
  2. But the applet should establish an URLClassLoader pointing to the Jar, then invoke the constructor or main(String[]) of interest. If necessary, wrap the call in a SwingWorker.

Question:

I have an application that is running JVM inside it, it looks like it is using Abstract Windowing ToolKit (AWT), I found that after doing some researches as the main application window is a MSAWT_Comp_Class, doing some analyzing on the application EXE I found what looked like links to import the Java classes (I am not sure):

So I guess the Java classes are there but unreachable, all I could find in the app is an RC_DATA content that has the above links, also found that the app is a Java app converted to EXE using Jexegen as Jexegen and some SDK links can be found using a hex viewer.

My question is if is there a way to extract the Java classes or read them from that application? maybe by knowing the structure of Abstract Windowing ToolKit (AWT) or Swing or Jexegen or how Java files are being included in the c# app after compiling.

I hope I could I ask my question clearly, I tried my best with my little knowledge.


Answer:

My question is if is there a way to extract the Java classes or read them from that application?

As you already figured out, .exe file contains resources of type RC_DATA. There are two entries of such type. The smaller one (named "1001") contains just string with a class name (it may be main class name) and bigger one (named "1000", about 600 Kb) contains actual classes. You can extract that resource with help of any resource extracting tool such as a "Resource Hacker".

Each *.class file starts with 4 bytes 0xCA 0xFE 0xBA 0xBE so you can iterate through content of extracted "1000" and save each class into separate *.class file. Each 0xCA 0xFE 0xBA 0xBE will mark new file start. And, obviously end of previous.

Then classes can be decompiled.

maybe by knowing the structure of Abstract Windowing ToolKit (AWT) or Swing

AWT and Swing is a just standard libraries to build UI. So it doesn't matter here.

Question:

Our Java application has a function which outputs a Java applet which can be uploaded to our online repository. Recently we have been having trouble with Oracle security updates which require applets to be codesigned unless Java security settings are lowered on the client's machine.

To fix this we are trying to codesign the applets server side when they are uploaded but I have run into some trouble. The codeisiging seems to work fine with a command like this (using a certificate from Digicert):

jarsigner -tsa http://timestamp.digicert.com -keystore ./keystore.jks -storepass pass /path/to/jar alias

But we still get an error that says:

This application contains both signed and unsigned code'

I believe this is occurring because the Java application outputs applets that contain a main jar file and then a few .class files. Is there anyway to avoid this error without getting rid of the .class files? We currently want to fix this without having to make any changes to the Java application that outputs that applets.


Answer:

You can only sign JAR files, not loose class files. Class files themselves do not have a place to put the signature information and it would be highly redundant if they did. In a JAR file, the signature hashes go into the MANIFEST and public keys appear in the relevant RSA or DSA files. You will want to do one of the following:

  • Recommended: Package all classes into signed JAR files. You can sign components too, signing means distributed-by not authored-by.
  • Have individual users add your applet location to their Exception Site List.
  • Have a company's system administrator add your applet location (or certificate hash) to their Deployment Rule Set.

Question:

I am using Processing's Android Mode to create a sketch. For now, I only want to display an ellipse using a custom Dot class. Eclipse is not detecting any errors. I will post the entire code for reference. The main activity's code is the following:

package com.example.yo;

import processing.core.PApplet;

public class MainActivity extends PApplet  {

public Dot dot = new Dot(50,50,155,200,20);

    public void setup() {
        background(0,0,0);
        stroke(255,0,0);
        strokeWeight(10);
    }

    public void draw() {
        dot.display();
    }
}

The Dot class is the following:

package com.example.yo;

import processing.core.PApplet;

public class Dot extends PApplet{
    //declaration of dot's fields
    public int x;
    public int y;
    public int redd;
    public int greenn;
    public int bluee;
    public Boolean through = false;

    //constructor
    Dot(int xPos, int yPos, int redness, int greenness, int blueness){
        x = xPos;
        y = yPos;

        redd = redness;
        greenn = greenness;
        bluee = blueness;
    }

    public void display(){
        noStroke();
        fill(redd,greenn,bluee);

        if (through){        
            ellipse(x, y,40,40);
        }else{
            ellipse(x, y, 30, 30);
        }

    }
}

When I try to run the app, the app crashes instantly and the message box 'Unfortunately, Yo has stopped'. I have to admit that I cannot point you more precisely to my problem, since I have no clue as to what is wrong in the code. The Dot class is structured equivalently to the example given on the Processing help page: https://www.processing.org/reference/class.html Both classes are within the same package.

I have tried to instantiate the dot within the setup function, outside of it, or even continuously in the draw loop, with no success.

Please let me know if you need more info. Thank you in advance.


Answer:

Issue solved. For future reference:

The dot class should in no case extend PApplet, this only should be the case for main activity. However, when the dot class does not extend PApplet, Eclipse gives errors, which is not surprising, because it does not understand any of the processing commands. To solve that, The PApplet class should be declared at the beginning and then in the constructor PApplet should be passed as an argument and assigned to the variable we declared at the beginning. Now, all processing commands should be treated as methods of the parent class. This is the following code for dot (the only change I put in the MainActivity class is to call Dot with this as an additional argument):

package com.example.yo;

import processing.core.*;

class Dot{
    //declaration of dot's fields
    public float xpos;
    public float ypos;
    public int redd;
    public int greenn;
    public int bluee;
    public Boolean through = false;
    PApplet parent;

    //constructor
    Dot(PApplet p, float xPosition, float yPosition, int redness, int greenness, int blueness){
        parent = p;
        xpos = xPosition;
        ypos = yPosition;

        redd = redness;
        greenn = greenness;
        bluee = blueness;
    }
    public void display(){
        parent.noStroke();
        parent.fill(redd,greenn,bluee);

        if (through){        
            parent.ellipse(xpos, ypos, 4.0f, 4.0f);
        }else{
            parent.ellipse(xpos, ypos, 30.0f, 30.0f);
        }       
    }   
}

The solution to the issue is best described here:

https://processing.org/tutorials/eclipse/

under the section Processing in Eclipse with Multiple Classes.

Question:

I am trying to write a simple free hand drawing code in java using Point class and arraylist but i am getting stuck. Firstly, cant really leave the origin point, and secondly ther's always a line drawn between the 2 points even when mouse is not dragged.

public class FreeDraw extends Applet implements MouseMotionListener
{
     int x,y,m,n;
     ArrayList<Point> al;
     public void init()
     {
         al = new ArrayList<>();

        this.addMouseMotionListener(this);

     }
      public void paint(Graphics g)
      {

          for(int i=0;i<al.size();i++)
          {
               m=al.get(i).x;
               n=al.get(i).y;

               g.drawLine(m,n,x,y);  

               x=m;
               y=n;

          }
      }
     public void mouseDragged(MouseEvent e)
     {
        al.add(new Point(e.getX(),e.getY()));
        repaint(); 
     }


    public void mouseMoved(MouseEvent e)
    {
    //do nothing
    }

}

Answer:

You need to seed the initial x/y position (otherwise m and n will be 0x0 to the first point)

Something like...

@Override
public void paint(Graphics g) {
    super.paint(g);
    if (!al.isEmpty()) {
        int x = al.get(0).x;
        int y = al.get(0).y;
        for (int i = 1; i < al.size(); i++) {
            m = al.get(i).x;
            n = al.get(i).y;

            g.drawLine(m, n, x, y);

            x = m;
            y = n;

        }
    }
}

for example.

Apart from the fact that Applet was replaced with JApplet some 16 years ago, the applet plugin is no longer supported by Oracle, but most of the browsers actively block it, making it a dead end technology.

See Java Plugin support deprecated and Moving to a Plugin-Free Web for more details

Question:

I'm trying to get a Java applet to display in the browser - I know this question has been asked a number of times but I can't seem to find the answer that works specifically for this case - over the past few days I've tried everything from moving the HTML file to various places in the directory structure to using <applet> vs. the deployJava() API.

The code runs fine as a standalone applet in Eclipse, but when I try to run it in the browser I get either a "ClassNotFound" or "ClassDefNotFound" exception. I've packaged the code into a .jar and placed the .jar within the same folder as the HTML file, with my java code as follows:

package myPackage;
import java.awt.*;
import java.applet.*;

public class myClass extends java.applet.Applet{
    public void init(){
        String latLong = getParameter("unUsedParameter");
    }

    public void paint(Graphics g){
        g.drawString("Hello World",50,25);
    }
}

and the Javascript code is as follows:

<script src="https://www.java.com/js/deployJava.js"></script>
<section id = "java">
    <script type="text/javascript">
        var attributes = {
            code:'myClass.class',
            archive: 'myApplet.jar',
            width:500, height:500
        };
        var parameters = {latLong: total_path}; 
        var version = '1.8'; 
        deployJava.runApplet(attributes, parameters, version);
    </script> 
</section>

I also tried using codebase: 'myApplet.jar' instead of archive: but that didn't work either - I keep getting one of the same two exceptions. HELP!

EDIT: First off, the code: attribute was incorrect in my original post, it should have read 'myClass.class' (this is corrected above). The answer that got it working was changing the code: attribute to code: 'myApplet/myClass' - thanks for your help!


Answer:

Change your 'code' parameter to 'myPackage.myClass', instead of 'myApplet.class'.

You have more insights about the declaration in this post, which I've shown a way that works Angular.js and Java Applet

ie:

<script>
    <!-- applet id can be used to get a reference to the applet object -->
    var attributes = { id:'cdigApplet', code:'cdig.CDigApplet', archive:'cdig-applet-1.0.jar', width:1, height:1, classloader_cache:'false'} ;
    var parameters = {persistState: false, cache_option:'no' } ;
    deployJava.runApplet(attributes, parameters, '1.8');
</script>

My Applet

package cdig;

import java.applet.Applet;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Base64;


/**
 *
 * @author Ulysses Marins 
 */
public class CDigApplet extends Applet
{

    private static final long serialVersionUID = 1L;

    String ret;

    CDigApplet applet = this;

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public String signFile(String fileID, String pin, String token)
    {
        AccessController.doPrivileged(new PrivilegedAction()
        {
            @Override
            public Object run()
            {
                try
                {
                    File objFile = new File(token);

                    System.out.println("Iniciando processo de assinatura.");

                    objFile.sign("json", sig);

                        System.out.println(ret);
                    } else {
                        throw new IllegalArgumentException("Não foi possível iniciar processo de assinatura.");
                    }

                }
                catch (Exception e)
                {
                    String sl = "{\"success\":false," + "\"message\":\"" + e.getMessage() + "\"}";
                    ret = sl;
                    System.out.println(sl);
                }

                return null;
            }
        });

        return ret;
    }

    public void init(){
    }

    public void destroy(){
    }

}

Question:

I am trying to integrate an existing applet packaged as jar file in an existing GWT application built with maven.

Now I am not being able to figure out, why the applet class is not being found. A ClassNotFoundException is being thrown when I try to load the applet, saying that the applet class cannot be found.

The GWT Maven project has several modules and the applet I want to integrate is in its own Maven module. The applet jar file is being signed and packaged as in the final war file for the GWT app by the maven build process.

When I deploy the war file in a Tomcat server I have the following structure under the webapps folder:

webapps
  my_gwt_app
      WEB-INF
        classes
        deploy
        lib
          signed_applet.jar
          other_application_dependency.jar
        views
        web.xml

Here is the HTML result which is being generated by my GWT presenter:

<applet code="com.example.MyApplet.class" archive="/my_gwt_app/WEB-INF/lib/signed_applet.jar" width="1000" height="800" id="my-applet">
    <param name="permissions" value="all-permissions">
</applet>

Could someone tell me what I am doing wrong? Thanks!


Answer:

Nothing in the lib or classes directory is available to be served to clients that visit the site. It will be necessary to move the Jar to another place on the server.

In addition to that:

The following path is simply wrong.

archive="/my_gwt_app/WEB-INF/lib/signed_applet.jar"

WEB-INF would typically be the 'root' of the site.


<param name="permissions" value="all-permissions"> 

Whatever you are trying to achieve there, it will not add permissions to the applet.

Question:

We have a java applet which is working OK in most client environments, primarily Windows 7, but recently we have been asked to support Ubuntu clients as well.

The problem is that when the applet is fired up on the Ubuntu client (running Firefox and the natively installed "IcedTEA" Java VM 1.7.0_75) we get this exception:

java.lang.VerifyError: Cannot inherit from final class
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at net.sourceforge.jnlp.runtime.JNLPClassLoader.access$1701(JNLPClassLoader.java:103)
    at net.sourceforge.jnlp.runtime.JNLPClassLoader$5.run(JNLPClassLoader.java:1636)
    at net.sourceforge.jnlp.runtime.JNLPClassLoader$5.run(JNLPClassLoader.java:1634)
    at java.security.AccessController.doPrivileged(Native Method)
    at net.sourceforge.jnlp.runtime.JNLPClassLoader.findClass(JNLPClassLoader.java:1633)
    at net.sourceforge.jnlp.runtime.JNLPClassLoader.loadClassExt(JNLPClassLoader.java:1670)
    at net.sourceforge.jnlp.runtime.JNLPClassLoader.loadClass(JNLPClassLoader.java:1471)
    at com.renosci.Nlx.chartapplet.NlxBrowserJsEngine.<init>(NlxBrowserJsEngine.java:46)
    at com.renosci.Nlx.chartapplet.UtilityApplet.init(UtilityApplet.java:87)
    at sun.applet.AppletPanel.run(AppletPanel.java:436)
    at java.lang.Thread.run(Thread.java:745)

We don't get this exception under Windows (admittedly, different JVM builds and of on Windows we are using the Oracle supplied VMs instead of this IcedTea version).

I understand the meaning of the exception - and have a quick google search revealed multiple SO questions that mainly boiled down to the the suggestion that the build path is not the same as the class path, such that at compile time a base class was not final, but at runtime the classloader is finding it final.

However, I don't understand how that can be the case:

  • The class which is throwing the error is extending from an abstract base class that is part of our codebase, and according to our version control system has never been final

  • There is no possibility of there being any other versions of this class on the target machine that I am testing with - in fact I created a fresh VM for this test and got the problem straight away

I am assuming that the class it is complaining about NlxBrowserJsEngine, running immediately before the call to loadClass - is that correct? And that the base class of this class is the one which it thinks is final?

For completeness - here is the declaration of the class (which is the line 46 that the exception complains about) and the declaration of the only two fields it has:

public class NlxBrowserJsEngine extends NlxJsEngine {  /* Line 46 */
    private JSObject windowObj;
    static private Object evalLock = new Object();

JSObject is netscape.javascript.JSObject, provided by the Java browser plugin.

Here is the declaration of the base class:

public abstract class NlxJsEngine {

Thanks for any insights!


Answer:

I eventually tracked down the cause of this.

As indicated by @immibis's comments, the exception was during class initialization, rather during construction of an instance.

One of the methods of class NlxBrowserJsEngine calls a static method of another class - and this class extends from netscape.javascript.JSObject.

In the oracle implementation this JSObject class is not declared final, so extending it works fine.

In the IcedTea implementation, JSObject is final. Therefore when loading this class in the IcedTea JVM Plugin, an exception is thrown.

I'm not sure if this incompatibility was an oversight on behalf of the IcedTea implementors, or perhaps done deliberately (due to security perhaps?). Either way it caused big problems for us.

Through extensive refactoring it would have been possible to overcome this, however in our case this was not considered worthwhile so we have decided to require our users to install the Oracle JVM.

Question:

I am trying to make a simple Applet, and it is proving far more challenging than I expected.

I have the following, very basic applet:

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet
{
   public void paint (Graphics g)
   {
      g.drawString ("Hello World", 25, 50);
   }
}

created in notepad and saved as:

HelloWorldApplet.java

then in the same folder I have the following HTML file:

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>

created in notepad and saved as:

HelloWorldApplet.html

I am getting the following error when trying to load the page:

ClassNotFoundException

HellowWorldApplet.class

Java is installed on the machine and from all the tutorials and reading I have done, everything is exactly correct.

Any ideas??


Answer:

Embed the following code in the applet file as a multiline comment.

Eg:

/*
<applet code="HelloWorldApplet.class" width="320" height="120"></applet>
*/

save this as "HelloWorldApplet.html"

Compile using javac command

javac HelloWorldApplet.java

for Run the program using appletviewer command

appletviewer HelloWorldApplet.html

Question:

Can someone help me understand what is happening in this code?

public class aClass extends Applet{
    public void paint(Graphics g){
        g.drawRect(0, 0, 400, 200);
    }
}

My understanding is this, I create a class of name aClass that inherit(because it becomes a daughter) methods and attributes of the Applet class; then overwrites the paint method(which had been inherited from Applet), and this method expects an object as a parameter (which we put name g) created from the class Graphics, and then we call the drawRect method that is proper to the g object (which was created from the Graphics class); so that when the aClase class is executed, a rectangle is drawn, is it like that?


Answer:

Applets are an old, deprecated technology and you should consider newer technologies such as Java Web Start. That said, your understanding is mostly correct apart from some of the terminology.

I create a class of name aClass that inherit(because it becomes a daughter) methods and attributes of the Applet class;

Extending a class means that you create a new sub-class (in this case aClass) which is based off of the public contract and private implementation of the super class (Applet). The way that aClass behaves should respect the Liskov substitution principle at a high level meaning that anywhere you can use an Applet, you should be able to use an aClass too. This means respecting the public contract of Applet in aClass.

Applet class; then overwrites the paint method(which had been inherited from Applet),

Partially correct. aClass will override paint meaning that it will called when invoking paint on an instance of aClass rather than the default definition in Applet. It does not overwrite, as it is still possible to call the super implementation of this method. You should also annotate overriden method with the @Override annotation

@Override
public void paint(Graphics g){
    // calls paint from higher up the inheritance tree
    super.paint(g); 
    g.drawRect(0, 0, 400, 200);
}

this method expects an object as a parameter (which we put name g) created from the class Graphics,

Yes, or just like aClass extends Applet, this could be some class that also extends Graphics.

e.g. class FooGraphics extends Graphics { ... }

and then we call the drawRect method that is proper to the g object (which was created from the Graphics class);

Yup. Part of the public contract to the Graphics class.

so that when the aClase class is executed, a rectangle is drawn, is it like that?

Whenever the Applet framework decides to update the view it will call this method which has the effect of drawing a rectangle.

Question:

I am working on CTF challenge and there is a link with the challenge, that looks like that : 46.XXX.XX.XX:8008/ If I open the Developer Tools in that page, I can find an applet, with the attribute code with value of "mPage.class"

<applet width="700" height="230" codebase="out" code="mPage.class">
    <param name="_cx" value="13229">
    <param name="_cy" value="6085">
</applet>

Usually I would change the url and add mPage.class at the end For example, if the URL was : https://website.com/file.shtml I would type in the url bar: https://website.com/mPage.class And I could download the mPage.class file But since the url doesn't finish with "file.html" or something likes that. I can't do 46.XXX.XX.XX:8008/mPage.class

When I try to go to http://46.XXX.XX.XX:8008/mPage.class, my browser tell me that the Web page was not found. I don't know if I can actually download the class file. Because to get it, I should do something like : http://46.XXX.XX.XX:8008/../mPage.class But it obviously doesn't work. Since I can use the applet in the page, I should Theorically download it. If you find some mistakes, (like spelling one), don't hesitate to warn me, sorry English is not my native language. And thank you for reading.


Answer:

<applet width="700" height="230" codebase="out" code="mPage.class">
    <param name="_cx" value="13229">
    <param name="_cy" value="6085">
</applet>

The important part of finding the class files is to account for the codebase specified in the applet element, which effectively means that we need to look in the out directory (added to the path of the document) in order to find where the class files actually exist.

So this:

http://46.xxx.xx.xx:8008/mPage.class

Needs to be this:

http://46.xxx.xx.xx:8008/out/mPage.class

Question:

I wanted to know, why following code does not work:

public class ClockRunnable extends Applet implements Runnable {

Thread m_zeit;
Thread m_background;

 public void init() {
    m_zeit = new Thread(new ClockRunnable());
    m_background = new Thread(new Background());

    m_zeit.start();
    m_background.start();

  }
}

This is of course only an example code. I was wondering, because if I create a new Background Thread it works like written above. But if I call a new Thread for my ClockRunnable class, it throws me a NullPointerExecption. But if I change the new Thread command to

        m_zeit = new Thread(this);

It works perfectly.

If the example above is not enough, here is the whole code + ErrorOutput:

import java.util.*;
import java.text.*;
import java.awt.*;
import java.applet.*;

public class UhrzeitRunnable extends Applet implements Runnable {
String m_aktZeit;
DateFormat m_formatierer;
Font m_anzeigeFont;
Color m_farbe;
Thread m_zeit;
Thread m_background;

public void init() {
    m_anzeigeFont = new Font("Serif",Font.BOLD,22);
    m_formatierer = DateFormat.getTimeInstance();
    m_aktZeit = m_formatierer.format(new Date());
    m_zeit = new Thread(new UhrzeitRunnable());   // if I change it to "this" it works
    m_background = new Thread(new Background());
    m_zeit.start();
    m_background.start();

}

public void run() {
    while(true) {
        m_aktZeit = m_formatierer.format(new Date());  //NullPointerExeption on this line
        repaint();
        try {
            Thread.sleep(1000); 
        } catch (InterruptedException e) {
            return;
        }
    }
}

public void start() {
    if(m_zeit == null) {
        m_zeit = new Thread(new UhrzeitRunnable());
        m_zeit.start();
    }
    if (m_background==null) {
        m_background = new Thread(new Background());
        m_background.start();
    }
}

public void stop() {
    if(m_zeit!=null){
        m_zeit.interrupt();
        m_zeit = null;
    }
}

public void destroy() {
    if(m_zeit !=null) {
        m_zeit.interrupt();
        m_zeit = null;
    }
}

public void paint(Graphics g) {
    g.setFont(m_anzeigeFont);
    g.setColor(Color.blue);
    this.setBackground(m_farbe);
    g.drawString(m_aktZeit, 20, 45);
}


public class Background implements Runnable {
public void run() {
    while (true) {
        m_farbe = new Color((int) (255*Math.random()),(int) (255*Math.random()), (int)(255*Math.random()));
            repaint();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {

        }
    }
}
}
}

And the Error output. The background thread works perfectly by the way.

Exception in thread "Thread-3" java.lang.NullPointerException
at kapitel15.UhrzeitRunnable.run(UhrzeitRunnable.java:29)
at java.lang.Thread.run(Unknown Source)

Answer:

Applets are strange beasts, and it is very unusual for you to call a constructor on one. Usually this is done by the web page's Java applet driver which then calls the the Applet's init method. And when you do call the constructor, the init() is not called, leaving some of your key fields null. But why would you want to do this? The Applet that you create is a completely distinct object from the one that is being displayed, and changes in its state will not be reflected in the displayed object.

Question:

First of all I am a dotnet developer and don't know anything about java. I am using a java applet in my asp.net application. basically this plugin is used for uploading folders which is not supported without using a plugin. I also have some telerik controls being used in one of my other pages. the problem is that when i try to run the page, I get a ClassNotFoundException in java.

I think this has got something to do with the telerik configurations in my web.config file

When I use the same applet in a different application which does not have any telerik controls or settings in the config, the applet works fine.

If anybody else has come across this issue or if you can tell me where I am going wrong, it would be really helpful.

Here's what I have in my aspx page.

 <applet width="200" height="30"
    codebase="assets/applet"
    id="PGatewayApplet"
    name="PGatewayApplet"
    code="com.gatewaytest.pgateway.applet.PGatewayApplet.class"
    archive="PGatewayApplet.jar,dcm4che-core-2.0.22.jar,log4j-1.2.13.jar,slf4j-api-1.5.0.jar,slf4j-log4j12-1.5.0.jar">
    <param name="mayscript" value="yes" />
    <param name="Mode" value="FileUpload" />
    <ASP:PLACEHOLDER ID="ExtraAppletParams" RUNAT="server"></ASP:PLACEHOLDER>
</applet>

I don't have the code for this applet. this same thing works fine in another asp.net application which does not have any telerik controls in it.


Answer:

After a lot of digging, I found that the RadCompression key in my web.config file was causing the issue. here's the key

<add name="RadCompression" type="Telerik.Web.UI.RadCompression" preCondition="integratedMode"/>

I commented this in the config file and the applet started working.

Hope this helps the others.

Question:

I am having an issue with applets, which I have been stuck on for hours. I have made a simple calculator applet that runs fine in eclipse. I have also made a simple html document (I have altered it more times you can imagine in efforts to make it work) which incorporates my calculator applet. The problem is, that whenever I hit "open with firefox" on my html document, I get the following error:

Now, I understand that this question has come up before on the internet, but I have been searching through so many forums for so many hours, and I still haven't figured it out.

I have tried many things in an attempt to resolve this.

I have already tried enabling heck Use SSL 2.0 Compatible ClientHello format.

I have tried cleaning the Java cache by going to the Java control panel, clicking Settings under Temporary Internet Files and clicking Delete Files. None of these things did anything.

I also tried saving the java class originally in eclipse into a .java in notepad and put that and the applet into the same directory, which again, did nothing.

And now, instead of my previous attempts of moving the .java file, I have moved the .html file into the src folder where all my code is, as shown in this screenshot:

This directory is in my workspace in src

Here is my html code, which incorporates the java code:

<html>
<head>
<title> Hello </title>
</head>
<body>
<APPLET code = "myappletclass.java" width = "400" height = "100"
alt = "Not working"
>
</APPLET>
</body>
</html>

This is my html code after millions of revisions, so chances are that I have already tried out a different form of this(i.e. without the alt, or with APPLET in lowercase ... ) but I am completely open to all suggestions.

Here is the java code that goes with it:

import java.awt.*;
import javax.swing.*;

public class myappletclass extends JApplet {
 private double sum;

 public void init() { //started by the browser when the Java program   (myappletclass.class) is loaded and run by the browser. The programmer does not write a call to the init() method.

    double n1 = 0;
    double n2 = 0;
    boolean successone = false; //keeps try catch running
    while (!successone) {
        try {
            String fn = JOptionPane.showInputDialog("Enter first number:");  //Whatever they enter will be stored in string fn
            n1 = Double.parseDouble(fn);
             successone = true; //wont go through while loop because is true  now!

            sum += n1;
        }

        catch (Exception e) {
            JOptionPane.showMessageDialog(null, "ENTER A NUMBER", "Nu uh",  JOptionPane.WARNING_MESSAGE);

        }
    }
    boolean successtwo = false; //keeps try catch running
    while (!successtwo) {
        try {
            String sn = JOptionPane.showInputDialog("Enter second number:");      //Whatever they enter will be stored in string sn
            n2 = Double.parseDouble(sn);
            successtwo = true; //wont go through while loop because is true now!
            sum += n2;
        }

        catch (Exception e) {
            JOptionPane.showMessageDialog(null, "ENTER A NUMBER", "Nu uh",       JOptionPane.WARNING_MESSAGE);

        }
    }

}

public void paint(Graphics g) {
    super.paint(g); //call superclass of paint
    g.drawString("The sum is " + sum, 25, 25);
}
}

At this point of time I am desperate to figure out how this works. Again, I have spent countless hours on figuring out how to do this, so I would really really appreciate your constructive criticism and feedback about how to display my applet in firefox with my html document. I am excited to hear from you, thank you so, so much.

EDIT WITH APPLETVIEWER USING COMMAND PROMPT

I got it to work with appletviewer, but the whole point of me doing this was to see what it would look like in a real browser like firefox, with all my html and all. Instead, I got the same result as I would have got by just running it in eclipse.


Answer:

Thanks so much MadProgrammer for helping me figure out the answer, and preventing me from wasting 10 more hours! Here is what I did: I needed to add a codebase = file://linkatbrowserbar to my tag. After adding in the file:// blah/blah/blah I was confronted with a security popup saying my security won't allow this applet. Then, I went over into the java control panel in security, and added file://blah/blah/blah into the list of things I can pass into security. Then I opened it through my browser and that's it! It worked!

Also note that you will need to first compile it in command prompt to turn it into .class from .java. Then you can do all of these steps! :)

Question:

Using Eclipse I'm trying to edit an old java applet all I have is a .jar, but I can see the files not being able to edit.... the source code is incomplete, so I wanted to edit it and fix it... anyone knows what can I do?

P.S. I just want to modify and fix the program in that jar.


Answer:

Well first of all, applets are considered obsolete. (In case you didn't know). The files you are trying to see/edit are inside the .jar. So, for me, the easiest way to access the content of a .jar is just changing the extension from .jar to .zip, after that you can access as it was a regular folder and modify whatever you want there. After done, just change the extension to .jar ... Since .jar is like a "package", modifying code while still inside the .jar is not possible/recommended.

Edit: After being able to see the files, you might need a decompiler (as it was mentioned by Jason Braucht in his comment). Check this out:

http://www.javadecompilers.com/

it is an online tool and lets you decompile .class files ...

Question:

package Program1;

import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Scanner;

public class Demo extends Applet{
    static int i=0;

    public static void test(){
        i=50;
        System.out.println("This is my static method");
    }


    public void paint (Graphics g)  {
        test();
        g.drawOval (60, 20, i, i);
    }

}

I have two method paint and test. I want to execute test method only once which is going to initialize the value of i and that i am going to use in paint method. But the problem is when I am executing the program it is calling text method once and when I am re-sizing the Applet window it is calling that test method again and again.

For my program the text method do lot of computation so calling test method just to assign the value again and again is not a good choice. How to call that Demo class only once ?


Answer:

You can use Applet class init() method..which is specially provided for this purpose.

Question:

I have this code for when an applet button is pressed:

public void actionPerformed(ActionEvent e)
  {
    oval p;
    int x, y, height, width, fill;
    x = Integer.parseInt(xfield.getText());
    y = Integer.parseInt(yfield.getText());
    height = Integer.parseInt(heightf.getText());
    width = Integer.parseInt(widthf.getText());
    list.add(new oval(x,y,height,width));
    repaint();
}

I need to iterate through the list of ovals and draw them in this class:

public void draw(Graphics g)
 {
   ListIterator li;
   li = list.listIterator();
   while(li.hasNext())
   {
   g.drawOval(x, y, height, width);
   } 
}

How do I get my list into this class? Is there a way I can pass it to the class as a parameter?


Answer:

You could add a private List<oval> ovals; list to the class that contains the actionPerformed method, and add the ovals to that list (as it could like you're doing already).

Then you create a public List<oval> getOvals() method, and use that to access the list from your draw method in the other class.

Question:

I am developing applet code using jsp page.

    <APPLET 
      id = "app"
      codebase="<%=request.getContextPath()%>/lib/" 
      code="com.myDemo.test.RunApplet.class" 
      width=100 
      height=50 
      archive="myApp1.jar, myApp2.jar">    
   </APPLET>

My directory structure is :

DemoProject
  -- src (some classes & packeages)
  -- build
  -- WebContent
       -- css (some css file)
       -- script (some js file)
       -- WEB-INF
            -- jsp(some jsp file)
                 -- myApplet.jsp
            -- lib
                 -- myApp1.jar
                 -- myApp2.jar

When i execute myApplet.jsp it will throws the error

java.lang.ClassNotFoundException:com.myDemo.test.RunApplet.class

I had also apply

codebase = "."
codebase = "classes"
codebase = "classes/"

but still ClassNotFoundException.


Answer:

Note that anything in the WEB-INF folder is only readable to the back-end servlet, not by anything running in the browser including the applet[1].

If the two jars in the lib folder are only used by the applet, you can move the folder up to webcontent level. If your backend also uses them, you'll have to either copy them or create a servlet to serve them to the front-end.

[1]What is WEB-INF used for in a Java web application?

Question:

import java.util.InputMismatchException;    
import java.util.Scanner;
class Rectangle extends Shape
{
private double width,height;

Rectangle(double w,double h){
    super();
    width=w;
    height=h;
}
@Override
public void draw() {

}
}
class MyClass
{
    public static void main(String[] args)
    {
        try
        {        
            Scanner c=new Scanner(System.in); 
            String st="";
            System.out.println("enter the number of Shapes you want to add(0 will exit)");
            byte s=c.nextByte();
            if(s==0)
                return;
            Shape[] shapes=new Shape[s];
            for(byte j=0;j<s;j++)
            {                                      
               System.out.println("what kind of shapes do you want , r for Rectangle , c for Circle");                    
               st=c.next();
               if("c".equals(st))
               {
                   System.out.println("enter the radius and then the Name please");
                   shapes[j]=new Circle(c.nextDouble());
                   shapes[j].setName(c.next());    
                   break;
               }
               else if("r".equals(st))
               {
                   System.out.println("enter the width and height and then the Name please");
                   shapes[j]=new Rectangle(c.nextDouble(),c.nextDouble());
                   shapes[j].setName(c.next());
                   break;
               }
               else
               {
                   System.out.println("c or r please");
                   j--;
               }                   
            }  
            DrawShapes(shapes);                             
        }
        catch(InputMismatchException i)
        {
            System.out.println("a decimal number was expected , but text was found , so we will start from begining");
        }
        catch(Throwable e)
        {
            System.out.println(e.getMessage());
        }    
    }
    public static void DrawShapes(Shape[] shapes)
    {
       for(int i=0;i<shapes.length;i++)
         shapes[i].draw();
    }
}
explanation:

the shape class is an abstract class which contains getPerimeter , getArea, and draw abstract methods, The draw method of the Rectangle class should draw the rectangle in a window.

Goal

draw the rectangle on a separate window while keeping my application a console one for the other methods.


Answer:

Suggestions:

  • Use the Swing GUI library, not AWT.
  • You will want to draw in a class that extends JPanel
  • Override the JPanel's protected void paintComponent(Graphics g) method, and do your drawing inside of this method.
  • Be sure to call the super's method: super.paintComponent(g) inside of your override.
  • Then display the JPanel inside of whatever top-level Swing window that you desire, but it a JApplet, JFrame, JDialog, or inside of another JPanel if this is required. You can add this drawing JPanel to your applet in the JApplet's init() method simply via add(myDrawingJPanel);

Regarding:

is it possible to use applet without extending Applet class?

No I don't think so. If you want to create a GUI and display it inside of a JApplet or Applet, then you must override the class, and in particular override its init() method, and add your GUI to the applet there.

For more specific help, consider providing more information and code with your question.


Edit Regarding your edit:

this is a console application and I want to keep it like that, but I also want to draw the rectangle when calling draw method, the shape class isn't needed, it's just an abstract class and doesn't have implemented methods. in summery I want to use an applet to draw the rectangle while keeping my application a console one(except drawing).any help ?

Again, if you want to draw something and display it, you need a GUI and so might as well create and display a stand-alone GUI such as a JFrame or JDialog or at the minimum a JPanel in a JOptionPane. Again, you cannot and should not use an applet in any of this. Period. My previous recommendations still stand.

Question:

I created applet and using bouncycastle class for digital certificate.

I have make some changes for java 8 101 and sign this jar

but after changing it will throws below exception.

StackTrace :

java.lang.RuntimeException: java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1ObjectIdentifier
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.instantiateApplet(Unknown Source)
at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Caused by: java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1ObjectIdentifier

at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter$1.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
... 24 more

please help me to resolved this.


Answer:

Resolved

Thanks to all I have tried many thing but didn't find any solution.At last i tried below and its worked.

I made following changes and its work for me.

Added new jar file version is bcprov-ext-jdk15on-1.47.jar in lib folder and make entry for this jar file in MANIFEST.MF

After made changes in MANIFEST.MF i have signed both bcprov-ext-jdk15on-1.47.jar and applet.jar file and its work for me.

Thanks.

Question:

I have an extremely basic Java applet that isn't functioning in Safari as an exercise for an old textbook that isn't working. I'm using the legacy Java SDK version 1.6 on OSX El Capitan. The HTML is

<html>
<head>
<title>2-1 Test</title>
</head>
<body>
<applet code="HelloWorld.class"></applet>
</body>
</html>

And the Java program is:

import java.awt.*;
import java.applet.*;

public class HelloWorld extends java.applet.Applet{
TextField m1, m2, m3;
public void main(){
m1 = new TextField(60);
m2 = new TextField(60);
m3 = new TextField(60);
m1.setText("Good day to you!");
m2.setText("My name is Cynthia.");
m3.setText("This is the third line.");
add(m1);
add(m2);
add(m3);
}
}

HTML and Java file (compiled to HelloWorld.class) are in the same directory (no packages are involved).

UPDATE: Spaces have been removed from the filepath. The Java console now came up with the following:

basic: tap installed
basic: Creating PluginEmbeddedFrame served by PlaceHolderServerName-2581
basic: Done creating PluginEmbeddedFrame
basic: Added progress listener: sun.plugin.util.ProgressMonitorAdapter@7e29e923
security: Expected Main URL: file:/Users/Desktop/GreatIdeasInComputerScienceWithJavaExercises/HelloWorld.class
java.lang.ClassNotFoundException: HelloWorld.class
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)
basic: load: class HelloWorld.class not found.
java.lang.ClassNotFoundException: HelloWorld.class
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)
security: Accessing keys and certificate in Mozilla user profile: null
security: Reset deny session certificate store
security: Reset deny session certificate store
basic: Removed progress listener: sun.plugin.util.ProgressMonitorAdapter@7e29e923
basic: Dialog type is not candidate for embedding
basic: Dialog type is not candidate for embedding

Can anyone suggest what I would need to do to get Java set up properly so I can continue with the book?


Answer:

Take what's in your main method and place it in the init or run method. Applets typically don't have main methods.

Having said all that, applets are now deprecated and are generally no longer supported, with most if not all browsers actively blocking them and Oracle's decision to remove support for the applet plugin.

Maybe you should have a closer look at How to use Applets

Updated

Now that the error has changed, it would suggest that you've not compiled the .java file and/or it's not compiled in the location you're expecting it

Question:

I'm starting to work on an applet that will replace an existing one. Having never developed an applet before, I thought I'd get going with the popular HelloWorld example. I am able to run it a couple different ways: in the appletviewer, and also in a browser if I put the JAR file containing the HelloWorld class in the same directory as the HTML (i.e. http://localhost:8080/myApp). I also got it to work when I put the JAR in a directory called HelloWorld just below the myApp directory and specified the codebase parameter in the <applet> tag as HelloWorld. But when I try to specify WEB-INF directories such as classes or lib, I get a ClassNotFoundException. What am I doing wrong?


Answer:

But when I try to specify WEB-INF directories such as classes or lib, I get a ClassNotFoundException. What am I doing wrong?

Those directories are only meant for classes/jars that are used in JSP and servlets (i.e. the stuff the server needs). The resources inside them are available to site visitors. In this sense 'visitor' means a User Agent (i.e. a browser) or a client side plug-in (such as Flash or the JRE).

You can confirm this for yourself by pasting the full URL to the Jar in the web browser address bar and hit 'enter' to browser to it. The server will give a message back to the effect 'forbidden'.

See also the WEB-INF info. page which expands:

WEB-INF is the name of a folder found in Java web applications. It is used to store deployment information such as the web.xml, required library files and compiled class files. It is normally not accessible from web. Any files which you want to put on war but do not want to make to public then web-inf is the place where you can keep those files.

Question:

I'm learning Java and reading this book: https://www.fca.pt/cgi-bin/fca_main.cgi/?op=2&isbn=978-972-722-791-4.

In this book, I have a Java applet exercise. I can run it in Eclipse in appletviewer and works well. but I'm having trouble integrating the applet into HTML.

Here's my java code:

package packageteste;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Date;

public class Relogio extends Applet implements Runnable{


    Date data;
    Thread proc;
    Font f = new Font("TimesRoman", Font.BOLD, 40);

    public void start(){

        proc = new Thread(this);
        proc.start();

    }

    public void stop(){

        proc = null;

    }

    @SuppressWarnings("static-access")
    @Override
    public void run() {

        Thread th = Thread.currentThread();
        while(proc == th){

            data = new Date();

            try{

                th.sleep(500);

            }catch(InterruptedException e){}

            repaint();

        }

    }

    public void paint(Graphics g){

        g.setFont(f);
        g.setColor(Color.GREEN);
        g.drawString(data.toString(),20,60);
    }}

And now here's my html code :

<!DOCTYPE html>
<html>


<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>


<body>
<applet code = "packageteste.Relogio.class" width="700"></applet>
</body>


</html>

Answer:

  • code = "packageteste.Relogio.class" must not include .class
  • If you have your applet built into a .jar file use the archive="..." attribute to tell the browser what .jar it is.
  • If you don't have a .jar make sure the class packageteste.Relogio can be found as Relogio.class in the packageteste directory.

See also here: How to specify correctly codebase and archive in Java applet?

Question:

I am trying to run Java applet using Google Chrome browser. Everytime I am getting no class found exception. Here is my code.

HelloWorld.java

package my.first.pack;

import java.applet.Applet;
import java.awt.*;

public class HelloWorld extends Applet {

    /**
     * 
     */
    private static final long serialVersionUID = 2741715258812838900L;

    public void paint(Graphics g) {
        g.drawString("welcome", 150, 150);
    }

}

Hello.html

<applet code="my.first.pack.HelloWorld" width="300" height="300">  

Answer:

  1. Sign your applet and all the .jar dependencies with a certificate.
  2. Populate your manifest with all the tags mentioned below (it's in xml because I use maven, you can write in the way you prefer)
<codebase>http://location.of.your.jar/</codebase>
<permissions>all-permissions</permissions>
<Application-Library-Allowable-Codebase>http://location.of.your.jar/</Application-Library-Allowable-Codebase>
<Manifest-Version>1.0</Manifest-Version>
<Implementation-Title>App Name</Implementation-Title>
<Implementation-Version>0.1.0</Implementation-Version>
<Application-Name></Application-Name>
<Created-By>1.8.0_45</Created-By>
<Main-Class>package.YourClass</Main-Class>
<mode>development (or production)</mode>
<url>url of the application</url>
  1. Surround your java method with the doPrivileged
  2. Be sure that your browser has the java plugin enabled
  3. Put your http path of your web app in the java exception list
  4. If your url has _ (underscore/underline) probably it won't be recognized.
  5. Try to move your .jar to the same folder of your html, not using the /applet folder.
  6. Take a look on this post, I was having a similar issue.

Remember, this error saying that 'is not a function' is because your .jar is not loading - or you made something wrong with the js syntax, what I don't think so.

Question:

let's, create applet and add it to jsp page, environment in use is STS Spring Tool Suite

create New -> Dynamic Web Project -> name="WEBtest"

Java Resources -> src-> new packeg="firstPack.secondPack.mainPack.appletPack" -> new class="MyApplet"

package firstPack.secondPack.mainPack.appletPack;
import java.awt.Color;

import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MyApplet extends JApplet {
    @Override
    public void init() {
        super.init();
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    populateGUI();
                }
            });
        } catch (Exception e) {
            System.err.println("createGUI didn't complete successfully");
        }
    }
    void populateGUI(){
        JPanel panel=new JPanel();
        panel.setBackground( Color.LIGHT_GRAY);
        panel.add(new JLabel("QUAQ-QUAQ"));
        add(panel);
        this.revalidate();
    }
}

Run As -> Java Applet

Ok it works

web.xml was created automatically

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>WEBtest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

so...

Web Content -> new jsp="default"

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <h6>DUCK</h6>

    <h6>First TRY</h6>

    <applet code="firstPack.secondPack.mainPack.appletPack.MyApplet"></applet>

    <h6>Second TRY</h6>

    <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93">
        <param name="code"
            value="firstPack.secondPack.mainPack.appletPack.MyApplet">
    </object>

    <h6>Third TRY</h6>

    <embed code="firstPack.secondPack.mainPack.appletPack.MyApplet"
        type="application/x-java-applet;version=1.6" />

    <h6>Fourth TRY</h6>

    <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93">
        <param name="code"
            value="firstPack.secondPack.mainPack.appletPack.MyApplet">
        <comment> <embed
            code="firstPack.secondPack.mainPack.appletPack.MyApplet"
            type="application/x-java-applet;version=1.6">
            <noembed> No Java Support. </noembed>
        </embed> </comment>
    </object>


</body>
</html>

now drag and drop our project in "Server"

server is default to STS: "Privotal tc Server Developer Edition v3.1"

start the server

open browser at http://localhost:8080/WEBtest/

click on window

click on Details

CLASS_NOT_FOUND_EXCEPTION

here some project setting

since everything from "src" go to "WEB-INF/classes" then i assume that "code" parameter in applet is OK

nevertheless i also tried to extract java file into JAR, and add "archive" parameter, but yet CLASS_NOT_FOUND_EXCEPTION

i deleted all java version on PC, then installed Java SE Development Kit 8 Update 40 (64 bit),it also installed Java 8 Update 40 (64 bit)

after, i tried to open some example of applet from docs.oracle.com yet failed, thus it asked me to install Java 8 Update 40 without 64bit, so now i have both, but since applet examples works fine i doubting this is the problem and left it as it is

at the end of second day of googling i'm kinda desperate, yet it's important to make it work


Answer:

since everything from "src" go to "WEB-INF/classes" then i assume that "code" parameter in applet is OK

Only the server has access to the WEB-INF/classes and WEB-INF/lib paths. If you try to make a direct fetch on the applet (using the browser address bar) you'll likely see a 'forbidden' page.

Question:

Is it possible to start/run/execute a jar within an Applet? If it is possible, how can I do this?


Answer:

Yes, it is possible (but not simple).

It would require a signed and trusted applet with a custom security manager to handle the security for the loaded archives. The steps would be along these lines.

  • Set the custom security manager.
  • Establish an URL to the Jar.
  • Establish an URLClassLoader for the URL.
  • Load the class and instantiate it.
  • Call the main(String[]) method.

Question:

My applet needs classes which are part of external jars (signed jars) and native libraries. I deploy these jars within my applet.jar. To load classes from those jars I found com.jdotsoft.jarloader.JarClassLoader class to be useful. I first build a console app to test the functionality of my applet and the JarClassLoader works fine for me. Next I wrote MyApplet class with two additional public methods, let's say action1() and action2(). And, as described by the JarClassLoader, I wrote a MyAppletLauncher class. (see code below). To get a reference to the MyApplet object, instantiated by the JarClassLoader I added the getApplet() method to the JarClassLoader class.

MyApplet.java:

public class MyApplet extends Applet {
    public void init()    { ... }
    public void start()   { ... }
    public void stop()    { ... }
    public void destroy() { ... }

    public String action1() {
        ...
    }
    public int action2() {
        ...
    }
}

MyAppletLauncher.java:

public class MyAppletLauncher extends Applet {
    private JarClassLoader jcl;
    public void init() {
        jcl = new JarClassLoader();
        jcl.initApple("MyApplet", this);
    }
    public void start() {
        jcl.startApplet();
    }
    public void stop() {
        jcl.stopApplet();
    }
    public void destroy() {
        jcl.destroyApplet();
    }
    public String action1() {
        return ((MyApplet) jcl.getApplet()).action1(); // <-- ClassCastException
    }
    public int action2() {
        return ((MyApplet) jcl.getApplet()).action2(); // <-- ClassCastException
    }
}

My changes to JarClassLoader.java:

public class JarClassLoader extends ClassLoader {

    private Applet applet; // was JApplet

    public JarClassLoader() {
        this(ClassLoader.getSystemClassLoader());
    }

    public JarClassLoader(ClassLoader parent) {
        super(parent);

        ...
    }

    public void initApplet(String sClass, final Applet appletParent) { // 2nd arg was JApplet
        Class<?> clazz = loadClass(sClass);
        applet = (Applet) clazz.newInstance();
        ...
    }

    public Applet getApplet() {
        return applet;
    }
    ...

In my opinion it is clear that the instance of MyAppletLauncher cannot down cast the provided Applet instance to MyApplet because the MyApplet instance was created in a different namespace (= not by the same class loader). But my issue here is how do I get the action1() and action2() calls to the MyApplet object? Or more common, can I call the public interface of MyApplet from the MyAppletLauncher object?

I already tried several things, like

  • MyApplet implements MyInterface, and then cast to MyInterface
  • Change the type of member JarClassLoader.applet to MyApplet

But all result in a ClassCastException at some point.

Any suggestion is welcome. Thank you.


Answer:

I think you are missing the point of the launcher applet. It serves as a shim between the applet container and its system ClassLoader on one hand, and the JCL-loaded real applet and JCL on the other. There should be nothing in the launcher applet besides the applet lifecycle methods.

I am unsure how any methods other than lifecycle methods are being invoked on your launcher applet anyway. That can't be accidental, so just stop trying to do it. Implement all your applet's functionality in the real applet class and any helper classes you need, as if the launcher applet didn't exist.

If you must have external components looking up your applet and invoking methods on it, then modify or subclass JCL to provide additional shim methods, using the same model that it already uses for application lifecycle methods.

Question:

I have been working on an Intranet portal for my company and, recently, the project coordinator requested to add a way to connect to the internal servers via SSH through the portal. Questions aside how useful that would be, I have found a Java app to be the only reliable way to do so, and I have settled with JTA

Problem is that I can't seem to find a way to embed it properly in HTML.

This is what I started with:

<object type="application/x-java-applet" height="300" width="550">
  <param name="code" value="Main" />
  <param name="archive" value="jta25b.jar" />
  <p>Applet failed to run.  No Java plug-in was found.</p<
</object>

Being the param "code" the name of the Main.class that is listed on the Manifest file. The problem is that said Main.class is inside three subdirectories from the JAR's root, specifically "de/mud/jta/Main.class".

Then I found out about a param "codebase" that would in theory allow me to pinpoint the class' location, but I'm not even entirely sure that's how codebase is supposed to work since documentation regarding its use is pretty sparse. Either way, adding this line to the object element has not solved the issue:

  <param name="codebase" value="de/mud/jta/" />

So, while I haven't tackled with Java in a long time I have considered installing Netbeans to try and change the classes paths to make the app work from its root folder. A better solution would be much appreciated, though.


Answer:

de/mud/jta is the path to the Java package for the Main class. So the value of the code param should be de.mud.jta.Main

Question:

How do I go from the Eclipse project to making a file that will run the applet in a browser? From what I understand, I have to make it into a .jar file and then make an html file with the applet tag, like follows:

<html>
  <body>
    <applet name="TerisApplet.java" code = "TetrisApplet.jar">
    </applet>
  </body>
</html>

I do this and I run into nothing but trouble. Right now I am receiving a ClassNotFoundException. What am I doing wrong?

If someone can walk me through step by step from getting the Java Applet from Eclipse into an applet running over a browser, that would be awesome. This is for my own learning experience btw and not for school. I'm pretty good with Java I think but fairly new to applets.


Answer:

1) the code should be

<html>
    <body>
       <applet code="name.class"
                       width="500"
                        height="250"/>
       </body>
   </html>

2) you must add your .class file to the folder in which your html file is located for this just search your name.class file and ther would be two files one with a $ sign , copy them both to the folder which contains your .html file

In "name.class","name" means your class name and you can take width and height as you want this is just an example.

Question:

I was looking at an applet code and it struck me.

My Questions:

why is setForeground() used without an object here despite it being defined as a non-static method in the API

the code is as follows:

import java.applet.Applet;
import java.awt.*;
/*<applet code = "swings.class" height = "500" width = "500"></applet>*/

public class Swings extends Applet{
    public void init(){
        setBackground(Color.yellow);
        setForeground(Color.red);
        Font f = new Font("Comic Sans MS",Font.BOLD,25);
        setFont(f);
    }
    public void paint(Graphics g){
        g.drawString("Welcome to Applets",100,100);
    }
}

Answer:

setForeground is declared as public in Component, Swings is a subclass of Component,

which means setForeground will be inherited by Swings as its own class member, so you can call setForeground in Swings directly.

You can check jls for more details.

update

In java, if both non-static methods are in the same class, they can call each other directly, without creating a new instance.

Since setForeground is inherited by Swings, setForeground and init are both members of class Swings. So you can call setForeground in init directly.

Question:

I am making a Java Applet to sign PDF from client side and I encounter the following error when launching the applet in Internet Explorer :

This is my folder architecture :

Test/
├── Applet.html/
├── PDFSigningApplet.class/
├── jars/
│   └── bcpkix-jdk15on-1.49.jar
│   └── bcprov-jdk15on-1.49.jar
│   └── itextpdf-5.5.11.jar
│   └── itext-pdfa-5.5.11.jar
│   └── ...

Here is my HTML code :

<html> 

<head> 
<title>Test Smart Card Signer Applet</title> 
<script src="http://java.com/js/deployJava.js"></script>

</head> 

<body>
    <script>
        var attributes = {
                          codebase: '.',
                          code: 'PDFSigningApplet.class',
                          archive: 'jars/bcpkix-jdk15on-1.49.jar, ' +
                                  'jars/bcprov-jdk15on-1.49.jar, ' +
                                  'jars/signing-pdf-applet-1.0-SNAPSHOT.jar, ' +
                                  'jars/commons-imaging-1.0-20170517.221134-118.jar, ' +
                                  'jars/commons-imaging-1.0-SNAPSHOT.jar, ' +
                                  'jars/itextpdf-5.5.11.jar, ' +
                                  'jars/itext-pdfa-5.5.11.jar, ' +
                                  'jars/itext-xtra-5.5.11.jar, ' +
                                  'jars/xmlworker-5.5.11.jar',
                          width: '800',
                          height: '600'
                         };
        var parameters = {java_arguments: ''}; // customize per your needs Xmx256m
        var version = '1.8'; // JDK version
        deployJava.runApplet(attributes, parameters, version);
        console.log("Ran script");
    </script>
    ...

And here is the use of BouncyCastleProvider in my Applet.java :

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
...
BouncyCastleProvider provider = new BouncyCastleProvider();

The strange thing here is that all other external libraries seem to have been well imported but I get the exception with BouncyCastleProvider.

What I have already tried based on the similar questions found online :

  • Signed all of my jars using the following commands :

    jar ufm myjar.jar addToManifest

    jarsigner my.jar myKey

With this in my addToManifest :

Permissions: all-permissions
Codebase: file:///C:/Users/A667080/Desktop/Test/
Application-Name: PDFSigningApplet
  • Added a security exception for this site in my Java setup
  • I verified using 7-zip that my BouncyCastle jar contains the .class used in my applet

Did I miss anything ?


Answer:

Okay after a few more hours I finally found the issue. I had done all of those setps correctly but :

  • Java was caching all of my jar files so nothing could have changed meanwhile. To change this, go to Control Panel (or System Preferences) > Java > General > Settings and then uncheck the box that says "Keep temporary files on my computer"
  • I had not rebuilt my jars, so none of my changes affected my applet. To rebuild using Maven use mvn -U clean install or jar -cvf DigitalSignerApplet.jar *.class otherwise.

I hope it will help some people in the future.

Question:

Getting java.security.AccessControlException on calling getWidth() method of java.awt.image.RenderedImage class.

Code which is causing problem

new Dimension(this.image.getWidth(), this.image.getHeight())

In the above code this.image is of type java.awt.image.RenderedImage class

Full stack trace

java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessClassInPackage.com.sun.media.jai.util")
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPackageAccess(Unknown Source)
    at sun.plugin2.applet.SecurityManagerHelper.checkPackageAccessHelper(Unknown Source)
    at sun.plugin2.applet.AWTAppletSecurityManager.checkPackageAccess(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at javax.media.jai.ScaleOpImage.layoutHelper(ScaleOpImage.java:228)
    at javax.media.jai.ScaleOpImage.(ScaleOpImage.java:437)
    at com.sun.media.jai.opimage.ScaleNearestBinaryOpImage.(ScaleNearestBinaryOpImage.java:77)
    at com.sun.media.jai.opimage.ScaleCRIF.create(ScaleCRIF.java:123)
    ... 33 more

NOTE:

I have added following lines into my java.policy file

 permission java.lang.RuntimePermission "accessClassInPackage.*";
 permission java.lang.RuntimePermission "accessClassInPackage.com.sun.media.jai.opimage";

Still it didn't work. Has anyone faced this issue? I am running applet on jre version 1.8.0_45

UPDATE:

Same code will work fine with Java 7 if we add following entry to java.policy file

permission java.util.PropertyPermission com.sun.media.imageio.disableCodecLib", "read";

Answer:

Got it working. Following are the details of fixes I have done

1] Add permission:all-permissions to MANIFEST.MF: Actually my applet jar already had this entry in its manifest. But my jar had dependencies on jai-core, jai-imageio and jai-codec jars which didn't had this entry. So I generated a uber jar using maven shade plugin so that my applet jar and all its dependencies will be packaged inside one single jar and refer to its manifest which will have entry permission:all-permissions in it's manifest

2] After doing step 1 I was getting java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessClassInPackage.com.sun.media.jai.util")

This exception can be resolved in 2 ways

a] By adding entry permission java.lang.RuntimePermission "accessClassInPackage.com.sun.media.jai.util"; to java.policy file which can be found at location C:\Program Files\Java\jre1.8.0_45\lib\security

This approach is not so cool as it requires modification of java.policy file in every client system. So I used alternate approach of implementing PrivilegedAction as described in approach b

b] By implementing PrivilegedAction you have to implement it's run() method. All the code inside run() method will execute with privileges enabled so that you won't get any AccessControlException. You identify the code throwing AccessControlException and put that code inside overridden run() method so that the code will have necessary privileges.

For exaple in my case following code was throwing AccessControlException

graphics2d.drawRenderedImage(image, new AffineTransform());

To fix it I have created a private class in my class and implemented PrivilegedAction like below

 private final class DrawRenderedImage implements PrivilegedAction
{
    private Graphics2D graphics2D = null;

    public DrawRenderedImage(Graphics2D graphics)
    {
        graphics2D = graphics;
        // TODO Auto-generated constructor stub
    }

    public Object run()
    {

            graphics2D.drawRenderedImage(image, new AffineTransform());


        return new Boolean(true);
    }
}

As you can see I have put the code which was causing problem inside run method. Now run method can be invoked like below

AccessController.doPrivileged(new DrawRenderedImage(graphics2d));

Here AccessController class will invoke run method of PrivilegedAction instance.

By doing this you don't have to put permissions in java.policy file as mentioned in approach a

Question:

For me, the robot class works but using robot.mouseMouse(x, y); will be the x and y of the screen. How do I make it only do the confines of the applet itself? So in other words the coordinates 1,1 would usually be the top left of the screen, but instead I want it to be the top left of the applet..

How is this achievable?


Answer:

You could calculate the position. You can ask for it's Location

myApplet.getLocation();

And for its size

myApplet.getSize();

That way you can create a method

public void mouseToPosition(int x, int y){
    int zeroPosX = myApplet.getLocation().getX();
    int zeroPosY = myApplet.getLocation().getY();

    int newPosX = zeroPosX + x;
    int newPosY = zeroPosY + y;

    ...
    //now you have to check if it's in the bounds of the Applet, maybe throw an error
    //and you can add your click/move/whatever robot logic
}

Question:

I am still new to JUnit testing. I am writing junit tests for this method:

public void LoadApplet(JPanel panel) {
    AppletClass applet = new AppletClass();

    applet.init();
    panel.add(applet,BorderLayout.CENTER);
    applet.start();
}

Answer:

I wrote the unit test this way and it worked:

public void TestLoadApplet() {
  AppletClass instance = new AppletClass();

  JPanel panel = new JPanel(); // Creating a empty panel
  instance.LoadApplet(panel);
  assertEquals("java.awt.BorderLayout", panel.getLayout().getClass().getName());
  assertEquals("Applets.AppletClassName", panel.getComponent().getClass().getName());
  }

Question:

In Java, how do I create Graphics within a class and then get the Graphics for use in an Applet?

One attempt to create this class for the graphic is as follows.

import java.lang.*;
import java.util.*;
import java.awt.*;

public class Cords{


    public static Graphics cords;
    public static int w,h,n;
    private static int xC,yC;

    public static void Paint(Graphics g)
    {
        for(xC=0;xC<=w;xC+=n){
            g.drawLine(xC,0,xC,h);
            g.drawString(""+xC,xC,11);
        }
        for(yC=0;yC<=h;yC+=n){
            g.drawLine(0,yC,w,yC);
            g.drawString(""+yC,1,yC));
        }
        cords=g.create();
    }
    public static Graphics cords(int w, int h,int n){
        return cords;
    }

Which I then attempted to use in an applet...

import java.awt.*;

import java.applet.Applet;
import javax.swing.Timer;

public class CordsTest extends Applet

    private int x,y,w,h,n;
    private Cords a;

    public void init()
    { 
        //w=getWidth();
        //h=getHeight();
        //a.cords(w,h,50);
    }

    public void paint(Graphics g){
        w=getWidth();
        h=getHeight();
        g.setColor(Color.black);
        paint(a.cords(w,h,50));

    }
}

As I am relatively new to asking questions on Stack Overflow, if there are any errors in question formatting, please have patience and if possible, let me know via comment so I can avoid these in the future. Thank you!


Answer:

paint is called automatically by the painting system when it wants your component to be repainted.

In order to do any painting, you should pass a reference of Graphics to an instance of you painting class, for example.

Using something like...

public class Cords{


    public void paint(Graphics g, int w, int h, int n)
    {
        for(int xC = 0; xC <=w; xC += n){
            g.drawLine(xC,11,xC,h);
            g.drawString(""+xC,xC-(n/5),11);
        }
        for(int yC = 0; yC <= h; yC += n){
            g.drawLine(25,yC,w,yC);
            g.drawString(""+yC,1,yC+((n/5)/2));
        }
    }
}

In your applet, you need to create an instance of Cords and then pass it a reference of Graphics

public class CordsTest extends Applet implements ActionListener{

    private Cords cords;

    public void paint(Graphics g){
        w=getWidth();
        h=getHeight();
        g.setColor(Color.black);
        if (cords == null) {
            cords = new Cords();
        }
        cords.paint(g, w, h, 10);
    }

Take a look at Painting in AWT and Swing and Performing Custom Painting for more details.

Honestly, unless you REALLY have to, avoid applets, start with a nice simple JFrame and JPanel