4

Is it possible to display a web applet inside a java application's window?

It would be preferable if you could give an example code, as I am rather newbish with java.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Tyilo
  • 28,998
  • 40
  • 113
  • 198
  • 1
    Why do you want to do this? Applets and applications are two different concepts and applets are some kind of frame replacement that wraps the content for displaying it in a web browser. – Stephan Oct 31 '11 at 22:16
  • I strongly second Stephan's good advice. I recommend that you go to the Swing tutorials to see how to create JPanels, and gear your application creation towards making JPanels. This way you can display them easily in an applet or a standalone application or a dialog window or in another JPanel with ease. – Hovercraft Full Of Eels Oct 31 '11 at 22:18
  • 1
    @Stephan Because I want to make a client for an applet-based game. – Tyilo Oct 31 '11 at 22:23

2 Answers2

4

Have a look into the Javadocs:

  extended by java.awt.Container
      extended by java.awt.Panel
          extended by java.applet.Applet

Applet are Panels, and so you should be able to add them to a Frame. However, their initialization and invocation in a Frame (or JFrame) is different. Here is, btw. the JApplet version:

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by java.awt.Panel
              extended by java.applet.Applet
                  extended by javax.swing.JApplet

If the Applet's code is yours, I would put all interesting content into a JPanel, and either use this JPanel in a JApplet, or put it into a JFrame, and use it as an application.

If it is not your (J)Applet, and you don't have the code, I would test to add them to a (J)Panel in a (J)Frame.

user unknown
  • 35,537
  • 11
  • 75
  • 121
0

If you really want to do this, you can simply add the applet to a frame, because Applet is a subclass of Component.

JFrame frame = new JFrame();

// Create your applet to add to the frame
Applet comp = new YourApplet() {{
  // this calls the method that initializes the applet. usually the browser calls it
  init();
}};

// Add the component to the frame's content pane;
// by default, the content pane has a border layout
frame.getContentPane().add(comp, BorderLayout.CENTER);

// Show the frame
frame.pack();
frame.setVisible(true);

Note that this is a bad practice and should only be used if you can not access and change the applets source code! You could get into problems with it and I can not guarantee that this will work.

The better way is to create a main panel that contains the whole view and add it to the applet or frame, depending of the type of client (web or standalone).

Stephan
  • 4,395
  • 3
  • 26
  • 49