go to previous page   go to home page   go to next page

Answer:

import javax.swing.*

The * means to import all the classes in the package. It is OK (and common) to do this, even if you only use a few of the classes.


Small GUI Program

empty frame

Our first program just shows a frame. It is not a useful program. But it will get us started. Here is the complete program:

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

public class TestFrame1 
{
  public static void main ( String[] args )
  {
    JFrame frame = new JFrame("Test Frame 1");
    frame.setSize(400,300);
    frame.setVisible( true );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  }
}

First a JFrame is created by invoking its constructor. The argument to the constructor sets the title of the frame.

The setSize(400,300) method of JFrame makes the rectangular area 400 pixels wide by 300 pixels high. The default size of a frame is 0 by 0 pixels.

The setVisible(true) method makes the frame appear on the screen. If you forget to do this, the frame object will exist as an object in memory, but no picture will appear on the screen. Later on in a program, if you call setVisible(false) the frame will become invisible, but the software object will still exist and can be made visible again with setVisible(true).

It is easy to forget to include setVisible(true). If you run your GUI program, and nothing happens, check that you have called this method.

The setDefaultCloseOperation() method picks the action to perform when the "close" button of the frame is clicked. This is the little X button at the top right of the frame. If you forget to call this method with the appropriate constant, a click on the "close" button will make the frame disappear, but the program will still be running. (If this happens, and the program was started from the command line, hit control-C to kill it.)


QUESTION 3:

When the progran is running, can the user change the size of the frame?