CSC 161 Winter 2011 Week 1 Lab 1: Introduction to GUI

Creating a GUI requires, at the very least, that you create a top level window from the JFrame class. A JFrame is used to hold all the user interface components in your program and show them to the user. Look at the documentation for the JFrame class at this link. There is a lot there, and we do no have to understand it all today.

At the top of the page, you will see a tree-like structure as shown on the right. This shows the inheritance tree of the JFrame class. This shows a JFrame is a special type of Frame, which in turn is a special type of Window, which in turn is a special type of Component, which in turn is a special type of Container, which in turn is a special type of Object.

Basically,

  1. A Component is something that can be displayed on the screen so the user can interact with it.
  2. A Container is a special type of Component that can be used to hold and (with the help of other objects called Layout Managers) organize other components placed inside it.
  3. A Container can hold any Component, including another Container (Think of putting a small bucket inside of a bigger bucket). A Window is a special type of Container that cannot be placed inside of another Container.
  4. A Frame is a special type of Window, and a JFrame is a special type of Frame.

Useful JFrame Methods

On the JFrame page, Look at, and write down, the descriptions of the following methods and constructors:

  1. JFrame()
  2. JFrame(String title)
  3. void setDefaultCloseOperation(int op)

Useful Frame Methods

Because the JFrame class is a child of the Frame class, JFrame inherits all methods that the Frame class has. This is called Method Inheritance. Click on the link to java.awt.Frame in the inheritance tree at the top of the page. This will take you to the documentation page for the Frame class. Find and write down the descriptions for the following methods:

  1. String getTitle()
  2. void setTitle(String title)

Useful Window Methods

Find the page for the Window class and write down the descriptions of the following methods

  1. void pack()
  2. void setSize(int width, int height)
  3. void setVisible(boolean b)

Write a Program that displays a JFrame

Create a Netbeans project called Prog1. At the top of the file, right below the package statement, add the the import statement

import javax.swing.*;

You need the import because, if you look at the inheritance tree for JFrame, you will see that it is in the javax.swing package.

Use the knowledge you have gained to create a program that displays a JFrame with a title. You will need to create the JFrame object, set its title, set its size (300 by 200 is a good size), set its default close operation, and make it visible. Make sure the statement to make the frame visible is the last one.

Experiment with the program. Note that you can move the frame on the screen, and you can resize it, and minimize it, and maximize it.

Useful Container Methods

We need to add user interface components to our frame to make it interesting. To do this, we need to learn about the Container and Component classes.

Find the page for the Container class and write down the descriptions of the following methods. Remember that a Container can hold other Component objects. In that context, think about why it makes sense for a Container to have these methods.

  1. void add(Component comp)
  2. void remove(Component comp)
  3. void validate()

Find the page for the Component class. A Component is something that needs to be seen by the user so the user can interact with it. Find and write down the description of the following methods.

  1. void setBackground(Color c)
  2. void setForeground(Color c)
  3. Color getForegound()
  4. Color getBackground()

Fun With Colors

Let us see if we can change the color of the JFrame from drab grey to something more exciting. Like red. Yeah, Red will be good. Now a JFrame is a Component, and you can set the background color of any Component. So, assuming that you have a reference called myFrame for your JFrame, Insert the following statement to change its background color to Red:

myFrame.setBackground(Color.Red);

Run the modified program.

Getting colors to show on a JFrame

What a disapointment! That did not work. The reason is that a JFrame contains a Container object inside it, called its called its content pane. When you add components to a JFrame, you are really adding them to the JFrame's content pane. The content pane sits on top of the JFrame and completely covers The color that you see when you look at a JFrame is really the color of its content pane. You must change the color of the content pane if you want the result of the color change to be visible. You can do that by using these statements:
Container cPane = myFrame.getContentPane();
cPane.setBackground(Color.Red);

Now run the modified program. It should work.

Let's get fancy

You can replace the two statements above with this one statement:

 myFrame.getContentPane().setBackground(Color.red);

More Fun with Colored JFrame objects

  1. Modify the program to get the JFrame to show up in different colors, blue, green, yellow, and others. Run the program.
  2. Modify the program so that is creates and displays two JFrame objects, one green, and one yellow. Set the green frame to EXIT on CLOSE, but set the yellow frame to HIDE on CLOSE. Run the program several times, closing the frames in different orders. What do you think is going on?
  3. Modify the program so that both frames are set to EXIT on clode. Run the program several times, closing the frames in different orders. What do you think is going on?

Adding Components to a JFrame

You can create a JButton object using the constructor

JButton(String text)
and then add the button to the JFrame using the add method:
JButton myButton = new JButton("Nice Button");
myFrame.add(myButton);

Try it, and run the resulting program. Try changing the size of the frame and not that the button grows or shrinks to fill the entire frame.

Modify the program to set the Background color of the button to yellow, with and the color of the the frame to Blue. Run the program and make observations.

Modify the program to add a second button to the frame, with text

Naughty Button

Run the program and note the effects.

Modify the program to add the two buttons in a different order. Run the program and observe. What can you conclude?

Layout Managers

A layout manager is an object that arranges components added to a Container. There are different types of Layout Managers, with each one arranging components differently. Some Containers already come with a default layout manager.

By default, the content pane of a JFrame comes preequipped with a special type of layout manager called BorderLayout. BorderLayout divides a container into 5 regions, called the NORTH, SOUTH, EAST, WEST, and CENTER, like this:

You can place a JButton in the SOUTH region of a BorderLayout of the content pane of a JFrame like this

  JButton sButton = new JButton("SOUTH");
  myFrame.add(sButton, BorderLayout.SOUTH);

And you can use similar code to place JButton objects in the other regions of BorderLayout. Modify your program to create 5 buttons, appropriately labeled, and place them on the JFrame. Each button should go into its own region.

By default, BorderLayout places components in the CENTER region if you omit the placement constraint. For example, if you write

myFrame.add(myButton);

and do not specify which region to put the button in, it goes in the CENTER.

If you place more than one component in the same region, only the last one placed will be visible.

FlowLayout

FlowLayout is a different type of Layout Manager. Unlike BorderLayout, FlowLayout does not divide a Container into regions. Instead, FlowLayout arranges components in a row as they are added. If the Container is long enough, all the components will line up in a row. If the container is then resized, so that it is narrower, the components will no fit in one row, so some of them will flow down to the next row. This is similar to how web browsers handle their content. When you resize the window for a web browser, its contents "flow" so they fit in the browsers new dimension.

Every Container object has a setLayout() method that can be used to install a Layout Manager in that container. Let us write a program that changes JFrame to use FlowLayout instead of the default BorderLayout.

Create a new Netbeans project, and call it FlowLayoutProject. We need to get the contentPane of the JFrame and change its layout manager to Flowlayout. This is done with code like this:

Container cPane = myFrame.getContentPane();
cPane.setLayout(new FlowLayout());

This code needs to come before you add any components to the JFrame.

Next, create a bunch of buttons and add them to the JFrame. You can do this one button at a time, or you can be slick and create an array of JButton and add them like this:

        JButton [] myButtons = {new JButton("Larry"), new JButton("Curly"),
                                new JButton("Moe")
                               };
        for (int k = 0; k < myButtons.length; k++)
            myFrame.add(myButtons[k]);

Next, you need to set the size of the JFrame. Because we have components added, use pack() to tell the frame to use a size just large enough to comfortably hold its contents:

  myFrame.pack();

Now make the frame visible, and run the program.

Challenge Your Programming Skills

  1. Extend the program so it has an array with more buttons, say two or three more. Run and resize the program different ways to see how it works.
  2. Modify the program to change the background color of the first button in the array to Yellow. Run the program and observe its effects.
  3. Modify the program to add an array of colors. The array of colors should be as large as the array of buttons, and have all different colors. Use this array to set all buttons to different colors. You can create an array of Color objects like this:
  4.  Color[] myColor = {Color.Red, Color.Yellow}; 
    Run the program and observe its effects.
  5. Modify the program to set the color of the content pane of the frame to some color different from all the buttons. Run the program and observe the effect.

Need more to do?

Did you get done before the end of lab? Use your imagination to explore. Look in the class text book and find related stuff to do. Or ask the instructor for a programming problem to work on.