NullPointerException in JApplet on Web Browser refresh?

Since finishing university and applying for jobs, I’ve decided to brush on up on my Java Skills. To kickstart the occasion, I decided to transform (and sometimes improve) all of my Java assignments to Web Applets, where most were command line ones.

Among numerous applet specific issues (they run fine in eclipse IDE), The biggest one is has been so far a big fat “NullPointerException” when refreshing the page.

It works fine on first load of the page, but when refreshing via F5 key, and a error results.
(every 2nd refresh works fine though)

Error-on-applet-refresh

Also, The “Details” button, which brings up the console, showed no errors, painfully annoying.

The Solution?

The solution is to assign the variable during program execution if you have created it as

public class myApplet extends JApplet{

static JTextArea console = new JTextArea(); //<-- This will be null on reload

public myApplet () {}
public void start() {
console = new JTextArea(); //<-- Added to stop Null pointer Error on reload
//other applet code
}

(or similar) just below the JApplet Class heading. Interesting though, Integers (Int type), are unaffected.

After implementing this fix, you can also, just drop the “new” code in the static area, is it will be made anyway, wasting computer time.

static JTextArea console;

So there you go, fixed.

Here’s some pictures that will help in understanding:

 

applet-running-perfect

fix-applet-refresh

Thanks for reading!

Joshua.

This entry was posted in Java Applets. Bookmark the permalink.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz