I am working on a game that I want to be embedded in a web browser and downloadable as a standalone jar. I have a subclass of JComponent that takes care of the game. I also have a subclass of JApplet and JFrame that display an instance of the game. If there some way I could do the following in my main method:

if (isEmbedded) {
    new AppletViewer();
} else {
    new FrameViewer();
}

or do I need to export twice, first using the AppletViewer and second using the FrameViewer?

有帮助吗?

解决方案

You might be able to use a structure like this:

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.setJMenuBar( applet.getJMenuBar() );
        frame.setContentPane( applet.getContentPane() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );

        applet.start();
    }
}

If the class is loaded as an applet the the applet is executed as is.

If the class is loaded into a JVM then the main() method is invoked and the applet components are added to the JFrame.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top