Eric Bernier
Eric Bernier

Reputation: 489

JApplet will not launch JComponent in browsers, works in Eclipse

I have coded a game proto-type in Java during my spare-time. This game was merely for my educational purposes only. I have it working fine via a JNLP launch file on the web, as well as on my main machine, via a JFrame.

My main intention is to make this proto-type playable in web-browsers via the use of a JApplet. I have coded a class, called AppletPlayer.java. The intention of this class is to essentially serve as a launcher for my Game's main class. The AppletPlayer.java file is pretty much as follows:

public class AppletPlayer extends JApplet {
private Game myGame_; // This is my game's main class
private boolean started_ = false;

public void init() {}

public void start() {

    if (!started_) {
        started_ = true;
        myGame_ = new Game();
        this.setContentPane(myGame_);
        myGame_.start() // I set focusable, and enabled to 'true' in the Game's start method
        // My Game class has no init method. Just a start method that spawns a new thread, that the game runs in
    }
}

Now, the Game class itself extends JComponent, and implements Runnable, KeyListener, and FocusListener. If I launch AppletPlayer via Eclipse it works like a charm in its Applet Viewer. However, when I deploy to the web I see two things:

  1. On a Windows XP machine the Applet loads, stays stuck on the main title screen, never receiving focus, hence never registering any type of user input.
  2. On a Windows 7 Machine the Applet loads, I hear my game's music, but the Applet screen itself renders a plain white box and nothing else.

These issues occur in both IE and Firefox.

I have been perusing Google and StackOverFlow for awhile now, trying to dig up a solution but haven't had any luck. I am a bit unfamiliar with Applets, and was hoping for a nudge in the right direction.

Upvotes: 0

Views: 271

Answers (1)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74800

One thing that may be the reason: Swing is not thread-safe, so all changes on the GUI (with includes your setContentPane) should occur in the AWT event dispatch thread. The start() method of an applet is not called on this thread.

Wrap all your GUI-related method calls in an EventQueue.invokeLater(...) call (or invokeAndWait, if you need some results, and SwingUtilities also has these methods, if you prefer) and look if you see some changes.

Upvotes: 1

Related Questions