0% found this document useful (0 votes)
115 views

Lab 7 Graphical User Interface (GUI)

This lab manual discusses creating graphical user interfaces (GUIs) in Java. It introduces AWT and Swing, the two main Java APIs for developing GUIs. It describes GUI components, containers, and event-driven programming. It provides steps to create a simple counter application using AWT components like labels, text fields, and buttons. It also outlines tasks for students to practice developing GUIs in NetBeans and being evaluated on additional GUI programming.

Uploaded by

Misbah Ullah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Lab 7 Graphical User Interface (GUI)

This lab manual discusses creating graphical user interfaces (GUIs) in Java. It introduces AWT and Swing, the two main Java APIs for developing GUIs. It describes GUI components, containers, and event-driven programming. It provides steps to create a simple counter application using AWT components like labels, text fields, and buttons. It also outlines tasks for students to practice developing GUIs in NetBeans and being evaluated on additional GUI programming.

Uploaded by

Misbah Ullah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Lab Manual for Advanced Computer Programming

Lab-07
Graphical User Interface (GUI)
Lab 07: Graphical User Interface (GUI)

Table of Contents
1. Introduction 64

2. Activity Time boxing 64

3. Objective of the experiment 65

4. Concept Map 65
4.1 AWT Packages 65
4.2 SWING Packages 65
4.3 Components & Containers 65
4.4 Event Handling 65
4.5 Creating a simple User Interface using Java AWT 66
4.5.1 Creating a component and adding it to container 66
4.5.2 Writing a simple GUI Counter Program using Java.awt 66

5 Homework before Lab 68


5.1 Problem Solution Modeling 68
5.1.1 Problem description: 68
5.2 Practices from home 68
5.2.1 Task-1 68
5.2.2 Task-2 68

6 Procedure& Tools 69
6.1 Tools 69
6.2 Setting-Up IDE [Expected time = 10mins] 69
6.2.1 Download NetBeans 69
6.2.2 Install NetBeans 69
6.3 Walkthrough Task [Expected time = 50mins] 69

7 Practice Tasks 87
7.1 Practice Task 1 [Expected time = 20mins] 87
7.2 Practice Task 2 [Expected time = 20mins] 87
7.3 Bonus Practice Task [Expected time = 1 day] 88
7.4 Out comes 88
7.5 Testing 88

8 Evaluation Task (Unseen) [Expected time = 55mins for two tasks] 89

9 Evaluation criteria 89

10 Further Reading 90
10.1 Books 90
10.2 Slides 90

Department of Computer Science, Page 63


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Lab 07: Graphical User Interface (GUI)

1. Introduction

Graphical user interface plays a very important role in the success of an application. GUI
provides an interface to the user which is user friendly and easy to operate. The GUI initiates
whole new level of programming which belongs to the category of event driven programming.
Event driven programming is the approach where every component of a program is registered to
the event handler. When the event occurs on a particular component then the handler associated
with it executes a block of code specially designed for that particular event.

A user interface is very important for every system that is being developed for interaction by the
user. In Java we can develop a very rich user interface. Java has predefined graphic classes
available in JDK for developing our own user interface. There are two main API’s for
developing user interface in Java.

 AWT API ( Introduced in JDK 1.0 now most of the parts are obsolete and replaced by
swing)
 SWING ( More Comprehensive, Enhanced state of AWT)

SWING and AWT have almost the same classes except one difference that the SWING classes
have character “J” as a prefix. For example JButton, JFrame etc.

In this lab we are going to work on making an attractive Graphical User Interface. You will also
learn how to use the Integrated Development Environment of Net Beans to develop the
application and interfaces quickly.

Relevant Lecture Material

a) Revise Lecture No. 25 and 26.


b) Text Book: Java: How to Program by Paul J. Deitel, Harvey M. Deitel
1. Read pages: 646-703

2. Activity Time boxing

Table 1: Activity Time Boxing


Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20mins 20mins
6.2 Setting up IDE 10mins 10mins
6.3 Programming with SWING 50mins 50mins
7 Practice tasks 20mins for each task 40mins
8 Evaluation Task 60mins for all assigned task 60mins

Department of Computer Science, Page 64


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

3. Objective of the experiment

 To get familiar with Event driven programming


 To be able to use Net Beans IDE
 To learn the techniques of developing user friendly interactive graphical interface and
understanding both API’s of Java dedicated for the development of user interfaces.

4. Concept Map

4.1 AWT Packages

AWT stands for Abstract Window Toolkit. AWT is a Java API which contains 12 Java packages
two are most commonly used java.awt and java.awt.event.

4.2 SWING Packages

Swing is also a Java API for GUI programming. It is bigger thenawtas it contains 18 Java
packages in jdk 1.7.

4.3 Components & Containers

Primary Java GUI entities are called component like button, label, text field etc. Components are
customizable. Containers hold the components and sub containers in a specific layout. Like
frame and applet are the containers which can hold other components. Figure 1 shows the
components contained in the container.

Figure 1: Components and Containers

4.4 Event Handling

When you press a button on an interface you are triggering an event. You write event listener to
control what will happen when the button will be pressed.There are two main parts of event
handling, a source like button or textfieldetc, and a listener associated with that source.

Department of Computer Science, Page 65


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

4.5 Creating a simple User Interface using Java AWT

4.5.1 Creating a component and adding it to container

Here are three basic steps

 Component declaration
 Initializing with appropriate constructor
 Identifying the container (Frame or panel)

Example

Label input_label; //declare a label


Input_label = new Label(“Enter ID”); // invoking a constructor
this.Add(input_label);
input_label.setText(“Enter Password”); //changing label text
input_label.getText();

4.5.2 Writing a simple GUI Counter Program using Java.awt

In this example we will insert a main frame and inside that frame we will insert 3 component
A label with text “Counter”, a textfield which should be non editable and a button count.When
someone will press a button count it will add +1 in the count value. Following steps will guide
you how create a simple form represented in Figure 2.

1. Include Java API’s in the body of the program

import java.awt.*;
importjava.awt.event.*;

2. Create a class which extends the main java.awt.frame class

public class AWTCounter extends Frame implements ActionListener {

3. Declare the Components

private Label lblCount; // declare component Label


privateTextFieldtfCount; // declare component TextField
private Button btnCount; // declare component Button
privateint count = 0; // counter's value

4. Call Constructor to setup GUI Components

publicAWTCounter () {
setLayout(new FlowLayout());
// "this" Frame sets its layout to FlowLayout, which arranges the components
// from left-to-right, and flow to next row from top-to-bottom.

Department of Computer Science, Page 66


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

lblCount = new Label("Counter"); // construct Label


add(lblCount); // "this" Frame adds Label

tfCount = new TextField("0", 10); // construct TextField


tfCount.setEditable(false); // set to read-only
add(tfCount); // "this" Frame adds tfCount

btnCount = new Button("Count"); // construct Button


add(btnCount); // "this" Frame adds Button

btnCount.addActionListener(this); // for event-handling

setTitle("AWT Counter"); // "this" Frame sets title


setSize(250, 100); // "this" Frame sets initial window size
setVisible(true); // "this" Frame shows
}

5. Writing the Main Method

/** The entry main() method */


public static void main(String[] args) {
// Invoke the constructor to setup the GUI, by allocating an instance
AWTCounter app = new AWTCounter();
}

6. Defining ActionEvent Handler (called when user press the button)

@Override
public void actionPerformed(ActionEventevt) {
++count; // increase the counter value
// Display the counter value on the TextFieldtfCount
tfCount.setText(count + ""); // convert int to String
}
}

Department of Computer Science, Page 67


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 2: GUI Based Counter

5 Homework before Lab


You must solve the following problems at home before the lab.

5.1 Problem Solution Modeling

After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you.

5.1.1 Problem description:

 Develop the understanding of all the packages used in AWT and Swing.
 Draw a hierarchy of component and container classes contained in AWT and Swing
packages.
 Revise different layout managers
(https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html )

5.2 Practices from home


Solve the following subtasks.

5.2.1 Task-1

Your task is to create a basic interface of small calculator, Insert a JFRAME Container and insert
3 textfields each with its label “First Number”, “Second Number”, “Results” respectively.Result
text field should be non-editable.Now insert 4 jbuttons “Multiply”, “Divide”, “Add”, “Substract”
each will the source of its event handler and perform a specified operation. And will show the
result in result text field.

5.2.2 Task-2
Find the component that best fits each of the following needs.

Department of Computer Science, Page 68


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

5.2.2.1 A component that lets the user pick a color

5.2.2.2  A component that displays an icon, but that doesn't react to user clicks.

5.2.2.3 A component that looks like a button and that, when pressed, brings up a menu of items for the
user to choose from.

5.2.2.4 Which method do you use to add a menu bar to a top-level container such as a JFrame?

5.2.2.5  Which method do you use to enable and disable components such as JButtons? What class is
it defined in?

5.2.2.6 Which Swing components use ListSelectionModel?

5.2.2.7 Do those components use any other models to handle other aspects of the components' state?
If so, list the other models' types.

6 Procedure& Tools

In this section you will study how to create an event driven program using NetBeans IDE.

6.1 Tools

NetBeans IDE 7 (Latest available version)

6.2 Setting-Up IDE [Expected time = 10mins]

6.2.1 Download NetBeans

Go to the following link to download latest version of NetBeans IDE with Java SE
support.http://www.oracle.com/technetwork/java/javase/downloads/jdk-7-netbeans-download-
432126.html

6.2.2 Install NetBeans

Install the downloaded NetBeans in your desired location then follow directions given in the next
section.

6.3 Walkthrough Task [Expected time = 50mins]


Follow the following steps to create a simple login form for your application after completing the
instruction given in section 6.2.2.

1. Go tostart  all programs NetBeans


2. Select Net Beans 7.1.2 from programs or the latest version that you have installed. Refer
Figure 3 for the place where you will find NetBeans.

Department of Computer Science, Page 69


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 3: Open NetBeans

3. Click on FileNew Project. New window of project will looks like Figure 4.

Figure 4: New Java Project

4. Choose the Java and then Java application then click Next. Figure 5 shows the window
that you will get after selecting Next Button.

Department of Computer Science, Page 70


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 5: Creating a Project

5. Enter the project name, location and click Finish. The new window looks like Figure 6.

Department of Computer Science, Page 71


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 6: New Project Window

6. Click on + sign of Project Tab on left of screen to Add/ View the files.

7. Click on Source package newJava Package to enter the package name to which your
class files belong to. After entering the name click finish when you are done. Refer
toFigure 7 and Figure 8 for preview of the process.

Department of Computer Science, Page 72


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 7: Add packages

Figure 8: Window to Enter a Package Name

8. Click on packagenewJFrameForm to create a new form as shown in Figure 9.

Department of Computer Science, Page 73


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 9: Create New JFrame form

9. New window will open up as shown in Figure 10. Enter the name of the form and click
finish.

Figure 10: Window to enter a new frame name

10. We named the form “First” so a new window will open as shown in Figure 11.

Department of Computer Science, Page 74


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 11: New Form Preview

11. Drag the Label Button from Right side Menu to Form as shown in Figure 12. After that
right click on the Label to edit text.

Figure 12: Drag and Drop Label and edit its text

12. Enter the Valid Field Name for example “USERNAME” as shown in Figure 13.

Department of Computer Science, Page 75


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 13: Changed JLable

13. Same as the JLabel, now drag the text field from menu and right click on text field and
choose “CHANGE VARIABLE NAME” as shown in Figure 14

Figure 14: Changing Variable Name

14. Enter the text field Name that is used for getting the input data. Preview is shown in
Figure 15.

Department of Computer Science, Page 76


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 15: Renaming Field name

15. Then right click on text field and choose “EDIT TEXT” as shown in Figure 16.

Figure 16: Process to edit text

16. Remove data from that field.The text field will be empty.

Department of Computer Science, Page 77


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

17. Insert another label for password and then on right click choose “EDIT TEXT” to name it
logiocally.

18. Drag the “PASSWORD FIELD” and drop it on the form as shown in Figure 17.

Figure 17: Password field insertion

19. Right click on password field and choose “CHANGE VARIABLE NAME” same s you
have already done for username field.

20. Change the password field name as shown in Figure 18.

Figure 18: Renaming Password Field

21. Right click on password field and choose “EDIT TEXT” and empty the field. Your form
should look like Figure 19.

Department of Computer Science, Page 78


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 19: Empty fields

22. Select the “BUTTON FIELD” from right side menu

23. Drag that field Button on the Form. It would look something like Figure 20.

Figure 20: Button field placed on the form

24. Right click on Button and select “EDIT TEXT” to give some logical name to the button
like the other fields. In our case we will have two buttons. One is ok and the other is
cancel button like the form shown in Figure 21.

Department of Computer Science, Page 79


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 21: Form with 6 fields

25. Now we will create a File containing user’s login information.


Note: use the file “users.csv” given at
“\\dataserver\jinnah$\Muhammad Aadil Ur Rehman\ACP-S3\users.csv”

26. After creating the file. Again go to NetBeans and make a new form that is looks like the
form shown in Figure 26.

Department of Computer Science, Page 80


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 22: New form

27. Create a file in which we will write a file reading code for the file that you have just
created. Right Click on “GUI PACKAGE” and select “JAVA CLASS” as shown in
Figure 27.

Figure 23: Process to create Java class

28. Enter the Class Name “FileConnectivity” and click on finish.

Department of Computer Science, Page 81


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 24: Naming Java Class

29. Write the file reading code to read from the file.

Public class FileConnectivity {

Public static Boolean verifyUser(String username, String password) throws IOException {


Boolean isExist = false;

File filename = new File(“users.csv”);


FileReader fr= new FileReader(filename);
BufferedReader br = new BufferedReader(fr);

String temp = null;


while((temp=br.readline()) != null)
{
\\break the temp
String [] userdetail = temp.split(“,”);
if(userdetail[0].equals(username) && userdetail[1].equals(password))
{
\\user matched

isExist=true;
break;
}
}

Department of Computer Science, Page 82


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

fr.close();
br.close();

return isExist;

30. Now open the first.java file

31. Right click on OK button

32. Click on EventActionActionPerformed as shown in Figure 30.

Figure 25: Registering with Action Listener

33. Write the code in that space provided for the method and make another method for
visibility of Form. Here get method is used for visibility. Figure 31 shows what to write
in actionperformed method.

Department of Computer Science, Page 83


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 26: ActionPerformed Method

34. Now click on second.java Right click on OK button.

35. Click on EventActionActionPerformedas was shown in Figure 30 and write the


code as shown in Figure 32.

Department of Computer Science, Page 84


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 27: ActionPerformed Method for Second.Java

36. Now go to main gui.java file.

37. The GUI project is now complete.What is left is just a testing part.

38. To RUN this project press F6

39. After you run the project the window will open up as shown in Figure 34.

Department of Computer Science, Page 85


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 28: GUI program output screen

40. Enter some data in the input fields. The correct data will be the one record you entered in
the Access database. Figure 35 shows where to enter the data.

Figure 29: Entering username and password

41. Press OK. If the username and password match with the database then a window showing
the successful login message will show up as shown in Figure 36.

Department of Computer Science, Page 86


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Figure 30: Successful login screen

7 Practice Tasks

This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\Advanced Computer Programming\Lab13
Develop them through text file first and then IDE. (NetBeans or Eclipse)

7.1 Practice Task 1 [Expected time = 20mins]

Create a Java interface using a jframe and four components on top of that frame, with title
“Yellow”, “Blue”, “Green”, “Gray” when user click on any button, the frame background color
as well as of that button’s should change accordingly.Frame’s title should be COLORS.

7.2 Practice Task 2 [Expected time = 20mins]

Create an Ideal weight calculator, by using following formula

Female Ideal Weight = Height2 /30, Male Ideal Weight = Height2 /28

Insert a main Jframe and two radio buttons for Male & Female Selection, and 5 Radio buttons
with labels with the range from 60 to 80 inches split each range with the difference of 4 and pick
the middle value. Also sets the default values of radio buttons.

Insert the Ideal weight text field, when user will change the selected radio button, it will update

Department of Computer Science, Page 87


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

the ideal weight read only text field. Your weight calculator should look something like the form
shown in Figure 37.

Figure 31: Ideal Weight Calculator

7.3 Bonus Practice Task [Expected time = 1 day]


Create an AWT accumulator applet A Java applet is a graphics program run inside a browser. Write
a Java applet (called AWTAccumulatorApplet) which contains:
1. a label "Enter an integer:",
2. a TextField for user to enter a number.
3. The applet shall accumulate all the integers entered and show it on the status bar of the
browser's window.

Figure 38 : AWT accumulator applet

7.4 Out comes

After completing this lab, student will be able to understand the usage IDE in developing event
driven applications.

7.5 Testing
This section provides you the test cases to test the working of your program. If you get the
desired mentioned outputs for the given set of inputs then your program is right.

Department of Computer Science, Page 88


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

Test Cases for Practice Task-1

Click on the buttons and check if the background colors change accordingly or not.

Input Output
Click on Green Button

Test Cases for Practice Task-2

Select different options from Gender and Height and check if the ideal weight value is according
to the formula

Female Weight = height2/30, Male Weight = height2/28

8 Evaluation Task (Unseen) [Expected time = 55mins for two tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

9 Evaluation criteria

The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

Department of Computer Science, Page 89


C.U.S.T.
Lab 07: Graphical User Interface (GUI)

10 Further Reading

This section provides the references to further polish your skills.

10.1 Books

Text Book:
 Java: How to Program by Paul J. Deitel, Harvey M. Deitel. Eighth Edition
 Java Beginners Guide: http://www.oracle.com/events/global/en/java-outreach/resources/java-a-
beginners-guide-1720064.pdf
 http://exampledepot.8waytrips.com/ for the package by package examples

10.2 Slides

The slides and reading material can be accessed from the folder of the class instructor available
at \\dataserver\jinnah$\

Department of Computer Science, Page 90


C.U.S.T.

You might also like