Question

Can I add program based on JFrame to JApplet ? How can I do that, when I try to do it like:

public class Test extends JApplet{
public void init(){
    JFrame frame=new JFrame(300,400);
    add(frame);
    frame.setVisible(true);
}

I got an error when i try to use appletviewer. Can anyone help me ?

Was it helpful?

Solution

You can't add a frame to an applet, but you can add an applet to a frame:

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

public class AppletBasic extends JApplet
{
    /**
     * Create the GUI. For thread safety, this method should
     * be invoked from the event-dispatching thread.
     */
    private void createGUI()
    {
        JLabel appletLabel = new JLabel( "I'm a Swing Applet" );
        appletLabel.setHorizontalAlignment( JLabel.CENTER );
        appletLabel.setFont(new Font("Serif", Font.PLAIN, 36));
        add( appletLabel );
        setSize(400, 200);
    }

    @Override
    public void init()
    {
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    createGUI();
                }
            });
        }
        catch (Exception e)
        {
            System.err.println("createGUI didn't successfully complete: " + e);
        }
    }

    public static void main(String[] args)
    {
        JApplet applet = new AppletBasic();
        applet.init();

        JFrame frame = new JFrame("Applet in Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( applet );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );

        applet.start();
    }
}

OTHER TIPS

To be complete your switch need to replace JFrame by a JApplet instance! That's it. JFrame is a top-level window in an ordinary runtime, JApplet is the top-level in an embedded runtime. So your code should be like :

public class Test extends JApplet {
  public void init() {
   JButton b = new JButton("my button");
   this.add(b);
  }
}

for an original code like :

public class Test {
 public static void main(String []a) {
   JFrame f = new JFrame("my test");
   JButton b = new JButton("my button");
   f.add(b);
   f.setVisible(true);
  }
}

Use JInternalFrame instead of JFrame. This will solve your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top