# Java: JFrame - Window

## Description

A JFrame is a window, which has a content pane which is where all components should be placed.

## Constructors

You can create a frame like this:

       JFrame w = new JFrame("your title");  // title is optional

Another better way is to define a class, eg MyWindow that extends JFrame, put the code which builds the GUI in the class's constructor, and create an instance of the window from the main program. See example below.

## Common methods

Assume w is a JFrame window.

    // Only one of getContentPane or setContentPane.  See Content Panes
       Container c = w.getContentPane();
       w.setContentPane(Container c);
    // Only one of setDefaultCloseOperation or addWindowListener See JFrame Close Box
       w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       w.addWindowListener(WindowListener listen);
    // Use pack or in rare cases validate.
       w.pack();     // finalizes layout.
       w.validate(); // only used for fixed layout sizes.
    // Only one of setVisible or show.  Should be last operation.
       w.setVisible(boolean visible);
       w.show();     // same as setVisible(true)
    // Misc.
       w.setResizable(boolean resizeable); // allow user to resize. Default true.
       w.setJMenuBar(JMenuBar mb);         // sets menubar
       w.setTitle(String title);           // Title in title bar.
       w.setSize(int width, int height);   // See Window Size and Position.

## Example

There would typically be a main method something like this.

      public static void main(String[] args {
        JFrame windo = new MyExample();
        windo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        windo.setVisible(true);
      }//end main

And a class which defines the window.

    public class MyExample extends JFrame {
      public MyExample() { // constructor builds GUI
        Container content = this.getContentPane();
        content.add(...) // add components to the content
        . . .
        this.setTitle("My new window");
        this.pack();   // does layout of components.
      }//end constructor
    }