Step 7

In all of the previous steps, we have worked within the context of the browser's window. There are times, however, when you may wish for your applet to have its own window. The code that follows does this. This is done using a Frame as the outer container, rather than a Panel.

Example Applet

import java.applet.Applet;
import java.awt.*;

public class step7 extends Applet{

// provides separate window for components and drawing

TextArea ta;
Button button;
MyPanel drawPanel;
Panel topPanel;
Frame outerBox;

  public void init ( ){

    ta = new TextArea ("My Text Area", 5, 40);
    button = new Button ("Button");
    drawPanel = new MyPanel ();
    topPanel = new Panel ( );
    outerBox = new Frame ( );

    setBackground (Color.white);
    setForeground (Color.red);

    topPanel.add (ta);
    topPanel.add (button);

    outerBox.setLayout (new BorderLayout ( ) );
    outerBox.add ("North", topPanel);
    outerBox.add ("Center", drawPanel);
    outerBox.setSize (600, 600);
    outerBox.setBackground (Color.white);

    outerBox.setVisible (true);

  } // end init

}// end step7

class MyPanel extends Panel {

  public void paint (Graphics g )  {

    g.fillRect (50, 50, 100, 100);

    g.setColor (Color.blue);
    g.setFont (new Font ("Helvetica", Font.BOLD, 24) );
    g.drawString ("Hello, World!", 200, 200);

    g.setColor (Color.yellow);
    g.drawOval (300, 50, 100, 100);

    g.setColor (Color.green);
    g.fillArc (50, 300, 200, 200, 180, -90);

    g.setColor (Color.cyan);
    g.fill3DRect (300, 300, 100, 100, true );

  }  // end paint

} // end MyPanel

Run the applet

Discussion

Because the new window does not "inherit" the window of the browser, we have to perform several additional functions, including setting its size and explicitly showing it.

Notice, also, that the program does not contain code to process the user's actions when he or she might wish to close or minimize the frame.  As a result, there is no way to get rid of it (except to kill the browser)!  For a solution to this problem, see the lesson on Java Events and the first lesson on User Interface Components (for a Frame that handles Window events).