CSC 160 Lab 2-1

GUI programs, boolean values and If Statements

In this lab, you will get an opportunity to create simple programs with a graphical user interface. In addition, you will work with boolean values, and learn to use conditional statements.

1. The First GUI Program

In class, we learned about the JFrame class, as well as several of its methods

        void setTitle(String title)
        void setSize(int width, int height)
        void setDefaultCloseOperation(int op)
    

Here is a GUI program that uses these three methods to create after creating a frame:

package lab2_2prog;

import javax.swing.JFrame;

public class Lab2_2Prog
{
    public static void main(String[] args)
    {
       //Create a frame
       JFrame frame =  new JFrame("CSC 160 GUI Program");
       //Set the size of the frame
       frame.setSize(400, 200);
       //Make the frame visible
       frame.setVisible(true);
       //Set the default close operation
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
    

Note how neatly the code is written, and notice that the statements are commented to explain what they do. From now on, you need to include comments in your code to explain what it does. More information on how to comment programs will be given later.

When executed, the program should display like this:

2. Setting The Screen Location of a Program's frame

The JFrame class has a method

        void setLocation(int x, int y)
    

that sets the location of the frame on the screen when it is shown. The x parameter is the distance of the left edge of the frame from the left edge of the screen, and the y parameter is the distance of the top edge of the frame from the top edge of the screen. Naturally, you should set the location of the frame before you make it visible.

Exercise 1. Modify the program so that it is located 300 pixels to the right of the the left edge of the screen, and 300 pixels down from the top of the screen.

Exercise 2. Modify the program so that it when it runs, it creates two frames with two different titlels, Frame One and Frame Two. The two frames should both be 300 by 150 pixels, and should both be 10 pixels down from the top of the screen, and should appear side by side separated by 10 pixels:

Exercise 3. Modify the program so that it when it runs, it creates two frames with two different titlels, Frame One and Frame Two. The two frames should both be 300 by 150 pixels. The second frame should appear to the right and below the first, to form a sort of downward staircase:

3. Setting the Colors of a User Interface Component

Each user interface component has a method

        void setBackground(Color c)
    

that allows you to set its background color. You can set the background color of frame by getting its content pane, and setting the color of the content pane. The content pane of a frame is an object of the Container class, so you would get the content pane and then set its color like this:

       // Get the content pane of the frame
       Container cPane = frame.getContentPane();
       // Set the color of the content panel to yellow
       cPane.setBackground(Color.YELLOW);        
    

The result will look as shown on the right.

The parameter to the setBackground() is an object of the Color class. The Color class provides patterns for creating different types of Color objects. It also contains static constant data values that are ``pre-made" colors that you can use. Examples of such objects are

        Color.RED  Color.PINK   Color.GREEN   Color.BLACK   Color.WHITE
    

and so on.

Exercise 4. Modify the two frame program so that the first frame is pink and the second frame is blue.

If Statements

Suppose we want to write a program that can distinguish numbers that are zero from numbers that are not. The program asks the user to enter an integer number. If the number is zero, the program prints "Zero", but if the number is not zero, the program prints "Not Zero". Here is a sample run

Enter a number:13
The number is not zero.
    

Here is another sample run

Enter a number:0
The number is zero.
    

This program will use an if statement. This is single statement that is made up of three parts: a boolean condition, and two other statements. If the boolean condition evaluates to true, the if statement executes the first statement and ignores the second. But if the boolean condition evaluates to false, the if statements ignores the first statement and executes the second. Think of an if statement as a fork in the road.

An if statement looks like this

        if ( boolean_condition )
        {
           // first statement, executed if boolean condition is true
        }
        else
        {
          // second statement, executed if boolean condition is false
        }
    

For our program, the boolean condition number == 0 checks if a number is zero. Here is the entire program

package lab2prog2;

import java.util.Scanner;

public class Lab2Prog2
{
    public static void main(String[] args)
    {
       // Create the scanner
       Scanner sc = new Scanner(System.in); 
       // Ask the user for anumber        
       System.out.print("Enter a number:");
       // Read the number
       int number;
       number = sc.nextInt();
       // Decide if the number is zero or not zero
       if (number == 0)
       {
           System.out.println("The number is zero.");
       }
       else
       {
           System.out.println("The number is not zero.");
       }       
    }
}

    

5. The Comparison Operators

The comparison operators are called relational operators. They are used to compare two values of primitive types to see if they are equal, or to see if one value is greater than another. There are six relational operators. All compare two values, and all yield a boolean result: true if the the comparison succeeds, false if the comparison fails.

Relational Operator Meaning
x < y x less than y
x <= y x less than or equal to y
x > y x greater than y
x >= y x greater than or equal to y
x == y x equal to y
x != y x not equal to y

Exercise 5. Write a program that asks the user to enter two integers. The program then determines whether the first integer is greater than the second. Here is a series of sample input/outputs.


Enter two  numbers:12 5
The first is greater than the second.
    

Enter two  numbers:-2 -5
The first is greater than the second.
    

Enter two  numbers:13 13
The first is not greater than the second.
    

6. Comparing Strings

In Java 8, the latest version of Java, you can use == and != to compare two string objects. You cannot, however, use the other comparison operators to test if one string is less, or less than or equal to, another string. In versions of Java before Java 8, using == and != to compare strings will not usually give you the value you expect.

Every object (including string objects) has a method

        boolean equals(Object obj)
    

that compares the object to another object to see they can be meaningfully regarded as being equal by looking at their data values. For example, two strings are regarded as being equal if they they have exactly the same sequence of characters: that is the two strings have the same characters in the same order.

Let us illustrate this with a program. The program will ask a user to enter a name. If the user's name is "Mary", the user is welcomed. If the user has any other name, he or she is told to go away. Here are two sample runs:


Who is there?: Mary
Welcome, Mary!
    

Who is there?: Henry
Go away!
    

Here is the program (Only the main method is shown).


    public static void main(String[] args)
    {
        // Scanner to read the name
        Scanner sc = new Scanner(System.in);
        // Ask for user's name and read the name
        System.out.print("Who is there?: ");
        String name = sc.next();
        // Invite Mary in, but send everyone else away
        if (name.equals("Mary"))
        {
            System.out.println("Welcome, Mary!");
        }
        else
        {
            System.out.println("Go away!");
        }
    }
    

Exercise 5. (Hand in for Grading) Pull all the knowldege you have learned in this lab together and solve the following problem. Write a program that asks the user to enter the width and height of a frame and reads in those values. The program then asks the user to enter a color for the frame. The program will be written to only recognise one color: green, and only if the word "green" is entered in all lower case letters. The program then creates and displays a frame with the given width and height. The frame displayed will be green if the user entered "green" for the color. Otherwise, the frame will be blue. This means that if the user enters pink, or "mouse", the color of the frame will be blue. In addition, the frame should display in its title the string entered by the user for the color.


Enter the width and height of the frame: 300 150
Enter color to use for the frame: green
    


Enter the width and height of the frame: 300 150
Enter color to use for the frame: Goat
    

Due Date: This is due Friday of Week 2. Try and get it done by Wednesday because there will be another assignment on Wednesday.