0% found this document useful (0 votes)
13 views287 pages

CCS103 - Module-Student-Copy-Comprog2 (20250119172915)

The document serves as an introduction to arrays in Java, covering definitions, declarations, and accessing elements. It outlines learning outcomes, necessary resources, and includes examples and activities for practical understanding. Key concepts include the structure of arrays, indexing, and methods for declaring and manipulating one-dimensional arrays.

Uploaded by

Intia, Ais B.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views287 pages

CCS103 - Module-Student-Copy-Comprog2 (20250119172915)

The document serves as an introduction to arrays in Java, covering definitions, declarations, and accessing elements. It outlines learning outcomes, necessary resources, and includes examples and activities for practical understanding. Key concepts include the structure of arrays, indexing, and methods for declaring and manipulating one-dimensional arrays.

Uploaded by

Intia, Ais B.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 287

PAMANTASAN NG CABUYAO |Introduction to Array 1

Course Material No. 1

Introduction to
Array
Jeruz Elises Claudel
Course Instructor
PAMANTASAN NG CABUYAO |Introduction to Array 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Define the basic of Java Arrays.


• To understand how accessing of Arrays works.
• To declare array in java programming.

RESOURCES NEEDED

For this lesson, you would need the following resources:

• Links to videos
• Links to websites
• Reference materials, tools, and equipment
PAMANTASAN NG CABUYAO |Introduction to Array 3

Before you start, try answering the following


questions.
MODULE CONTENTS
1. A data structure used in a Java Program to store
multiple values of the same type in a single
identifier.
Learning Lesson Title
_________________________________________
2. Each element in the array is identified by an.
2
________________________________________
3. Arrays indexes always starts at _____. 3 Pre-Test

________________________________________
4. These are individual values that are in the arrays.
4 Pre-Activity Exercise
________________________________________
5. What are the two possible ways in declaring an
array?
5 Introduction to Array
________________________________________

6 Array Declaration

9 Activity

Summary
10

11 Posttest
PAMANTASAN NG CABUYAO |Introduction to Array 4

Pre-Activity Exercise
Using Scanner create a program that will get the sum of a 5 length array.

Example:

.
PAMANTASAN NG CABUYAO |Introduction to Array 5

What is an Array?

When we say Array it is an arrangement of numbers, pictures or objects


that are formatted into rows and columns according to the type that are going
to use. Basically in programming, it is a collection of items or data that is
stored in a contiguous memory location, which is also known as database
systems. The purpose of an array is to simply store pieces of data of the same
type together.
When we talk about Arrays in terms of computer programming. This can
help you to locate and identify where we stored each piece of data, or element
by simply adding an offset to each value.

Each value in an array is called an element, and each element is accessed


by its numerical index. Always remember as shown in the illustration above
indexes always starts with 0. For example the 7th element is on index 6.
Another example the 10th element will be therefore our last index which is 9.
Since the Array length of our example is 10 our indexes will be 0 to 9.

How do we declare an Array?

Same as what we learned before in declaration variable type, an array can


be declared in two components. The two are what called Array with Value and
Array without Value.
PAMANTASAN NG CABUYAO |Introduction to Array 6

Example:

Array with Value:

Datatype identifier [ ] = {val1,val2,val3,val4,val5};

String name [ ] = {“Joey”, “Ross”, “Chandler”, “Monica”, “Phoebe”};

Array without Value:

Datatype identifier [ ] = new datatype sized[ ];

String name [ ] = new String [5];

You can declare different type of Arrays.


Example:

byte[ ] exampleByte;
short[ ] exampleShort;

long[ ] exampleLong;
float[ ] exampleFloat;

double[ ] exampleDouble;
boolean[ ] exampleBoolean;

char[ ] exampleChar;
int[ ] exampleInt;

We can also place the brackets after the array's name:

Example:
int exampleInt[];
PAMANTASAN NG CABUYAO |Introduction to Array 7

Accessing Array Elements

Let’s have an example first of an Array with Value.

An element is accessed by indexing the array name. This is done by placing


the index of the element within square brackets after the name of the array.

As an example we want to get the Element value “Chandler” so we need to


find its index number. Can you guess the index number of the Element Value
Chandler? Yes, that’s correct! It is Index 2 now we need to access it right now
by simply getting the Data type Identifier followed by the index number.

Example:

Identifier [index];
name [2];

//0 1 2 3 4 5
String name[] = {"Joey","Ross","Chandler","Monica", "Phoebe","Rachel"};

System.out.println(name[2]);
PAMANTASAN NG CABUYAO |Introduction to Array 8

We can also use for loop & for each loop to access all our arrays elements.

Example 1:

int num[] = {10,20,30,40,50};


for(int i = 0; i<num.length; i++)

System.out.println("Element at index "+ i + " : " +num[i]+" ");

Example 2:
int num[] = new int [5];
num[0]= 10;
num[1]= 20;
num[2]= 30;
num[3]= 40;
num[4]= 50;

for(int i = 0; i<num.length; i++)


System.out.println("Element at index "+ i + " : " +num[i]+" ");

Example 3:

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

// iterating through an array using the for-each loop


for (char item: vowels) {
System.out.println(item);
}
PAMANTASAN NG CABUYAO |Introduction to Array 9

Activity 1

Task: Write a program that will determine the common elements between two array
integers.
Example:
PAMANTASAN NG CABUYAO |Introduction to Array 10

Group Activity 1

Task: Write a program that will reverse the value of an integer.


Example:
PAMANTASAN NG CABUYAO |Introduction to Array 11

SUMMARY

Array Is a Collection of Multiple Values in a Single Variable with the Same


Datatype they are governed by using an index.

Elements are the individual values in an Array. And Index are numbers that
represents a position in a collection.

KEY TERMS

Array for Each Loop


Index Array Length
Element Value
For Loop
PAMANTASAN NG CABUYAO |Introduction to Array 12

POSTTEST
Directions: Fill in the blank with the letter corresponding to your answer.

_______ 1. If you declare an integer array as follow, what is the value of num[3]?
int num[] ={101,202,303,404,505,606};
a. 101 c. 303
b. 202 d. 404

_______ 2. This is a number that represents a position in a collection of an array.


a. Index c. Database
b. Element d. None of the Above

_______ 3. This number is the start of an index in an array.


a. 0 c. 5
b. 1 d. None of the Above

_______ 4. This are the individual values in an Array.


a. Index c. Indices
b. Elements d. None of the Above

_______ 5. If you declare a String Array as follows what is the value of name[0] ?
int name[] = {“Ross”, “Chandler”, ”Monica”, “Phoebe”, ”Joey”, “Rachel”};
a. Ross c. Monica
b. Chandler d. Program Error

_______ 6. If the array length is 10 what is the last index number of the array?
a. 1 c. 10
b. 0 d. 9

_______ 7. For the array: float stats[3]; What is the range of the index?
a. 0 to 2 c. 0 to 3
b. 1 to 2 d. 1 to 4

_______ 8. int nums[ ] ={2, 3, 5, 8, 9, 11}; How would you access the fourth element in nums?
a. Nums[0] c. Nums[3]
b. Nums[4] d. Nums[5]
PAMANTASAN NG CABUYAO |Introduction to Array 13

REFERENCES
[1] Arrays in Java from https://www.geeksforgeeks.org/arrays-in-java/
[2] Java Array Retrieved from https://www.javatpoint.com › array-in-java
[2] Java Arrays from https://www.programiz.com/java-programming/arrays
PAMANTASAN NG CABUYAO |Introduction to Array 1

Course Material No. 2

One Dimensional
Array
Jeruz Elises Claudel
Course Instructor
PAMANTASAN NG CABUYAO |Introduction to Array 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Declaring One Dimensional Array.


• Understanding Memory representation in Array.
• Using Interactive structures and functions for one
dimensional Array.

RESOURCES NEEDED

For this lesson, you would need the following resources:

• Links to videos
• Links to websites
• Reference materials, tools, and equipment
PAMANTASAN NG CABUYAO |Introduction to Array 3

Before you start, try answering the following


questions. Encircle your answer:
MODULE CONTENTS

1. Once an array is created, its size is already


fixed?
TRUE or FALSE Learning Lesson Title
2
2. Arrays create shorter and simpler codes in a
number of situations.
TRUE or FALSE
3 Pre-Test

3. Elements can be either primitive type or


reference type.
TRUE or FALSE
4 Pre-Activity Exercise

4. Identifiers determine the element that passes the


Array.
TRUE or FALSE
5 Introduction to Array

5. Java Array index always starts with 1.


TRUE or FALSE
11 Activity 2

12 Group Activity

Summary
13

14 Posttest
PAMANTASAN NG CABUYAO |Introduction to Array 4

Introduction
One-Dimensional Array from the name itself one-dimensional array
we know that this means it must deal with only one parameter. Entities of
similar types can be stored together using one-dimensional arrays. It can store
primitive data types (int, float, char, etc.) or objects.

When we say Array it is a group of variables which we also called


elements or components which contains values that have the same type. We
can say that Arrays are objects, that’s why it is considered reference types.
So we think of an array as actually a reference to an array object in
memory.

The elements of an array can be either primitive types or reference types.


To refer to a particular element in an array, we can specify the name of the
reference to the array and the position number of the element in the array. The
position number of the element is called index or also known as subscript.

How do we declare an Array?

A one-dimensional array can be visualized as a single row or a column of array elements that are
represented by a variable name and whose elements are accessed by index values.
PAMANTASAN NG CABUYAO |Introduction to Array 5

Declaration of one-dimensional array

So, let's see how we can declare a one-dimensional array in Java.

Datatype Identifier[ ];

Or
Datatype[] Identifier;

Remember an Array declaration has two components:

Data-type: This determines the data type of each element present in the array. (Char,int float,
objects etc.).

Identifier: It is the name of the reference variable.

[ ]: It is called subscript

Example:
int exampleInt[ ];
long exampleLong[ ] ;
float exampleFloat[ ] ;
char exampleChar[ ] ;

Now let’s learn how to create an actual one dimensional array.

Declare with Values


datatype identifier[]= {val1, val2, val3, val4, val5, val6}
int varNum[]= {1,2,-5,8,32};

Declare without Values


Datatype identifier []= new datatypesize[]
int varNum[] = new int[5];
PAMANTASAN NG CABUYAO |Introduction to Array 6

Memory Representation after construction

The new int[10] initializes and creates an object referenced as number and assigns memory to the
object in heap segment.

By default, the new operator initializes the elements in the array to zero (for numeric types), false
(for Boolean).
PAMANTASAN NG CABUYAO |Introduction to Array 7

One-Dimensional Array Examples

Example 1: Standard Method

int numVal[] = { 1, 2, 8, -10, 28,36 }; // initializing array


for (int i = 0; i < numVal.length; i++) {
System.out.println(numVal [i] + " "); // printing array elements
}

Example 2: Using Scanner

Remember in our previous lessons that Scanner is used to get user input and it is found in the
java.util packages.

public static void main(String args[]) {


// creating object of Scanner class
Scanner scan = new Scanner(System.in);

System.out.println("Enter length of Array: ");


int numLength = scan.nextInt();

int[] numElement = new int[numLength];


System.out.println("Enter the elements of the Array");
for (int i = 0; i < numLength; i++) {
// taking array input
numElement [i] = scan.nextInt();
}

System.out.println("One dimensional array elements are:");


for (int i = 0; i < numLength; i++) {
// printing array elements
System.out.print(numElement [i] + " ");
}
}
PAMANTASAN NG CABUYAO |Introduction to Array 8

Example 3: Using String

public static void main(String args[]) {


String[] array = { "Learning", "One-dimensional array", "in
java" };

System.out.println("String array elements are:");

for (int i = 0; i < array.length; i++) {


System.out.println(array[i]);
}
}

Example 4:
public static void main(String[] args) {

int array[] = { 87,68,94,30};


int total = 0;

for(int counter = 0; counter < array.length;


counter++)
total += array[counter];
System.out.println(total);
}

Example 5: Using math random


public class Main {
public static void main(String[] args) {
int[] array = new int[5];

for (int i = 0; i < array.length; i++) {


array[i] = (int)(Math.random() * 100);
}

System.out.println(Arrays.toString(array));

}
}
PAMANTASAN NG CABUYAO |Introduction to Array 9

Example 6:

public static void main(String args[]) {


int arraySample1[] = new int[10];
int arraySample2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int arraySample3[] = {4, 3, 2, 1};

System.out.println("length of a1 is " + arraySample1.length);


System.out.println("length of a2 is " + arraySample2.length);
System.out.println("length of a3 is " + arraySample3.length);
}
}
PAMANTASAN NG CABUYAO |Introduction to Array 10

Activity 2

Task: Write a program that will find the number based on your selected Array Length. The
program should do the following:
• The program can read at least 100 numbers.
• The program can determine the average length of an Array.
• The program finds the number of the items greater than the average.
• The program can enter an output.

Example:
PAMANTASAN NG CABUYAO |Introduction to Array 11

SUMMARY

An array is a collection of similar types of elements stored at contiguous


locations. It can store primitive data types (int, char, float, etc.) or objects.

One-dimensional array or single dimensional array must deal with values of


only one data type. One dimensional arrays can also store multiple objects of
the same class.

An array in java is an object of a dynamically generated class that can be


initialized and created using the new operator.

Array in java is index-based, the first element of the array is stored at the 0th
index, the second element at the 1st index, and so on.

One dimensional arrays in Java are static in size. This means, once created,
the size of one dimensional arrays cannot be changed.

KEY TERMS

Array for Each Loop


Index Array Length
Element One Dimensional Array
For Loop
PAMANTASAN NG CABUYAO |Introduction to Array 12

POSTTEST
Directions: Fill in the blank with the letter corresponding to your answer.

_______ 1. for(int i=0; i<10; i++). Which index holds the value of 5?
a. 1
b. 0
c. 2
d. 4

_______ 2. What is the sign of subscript in an array.


a. ; c. { }
b. [] d. None of the Above

_______ 3. This number is the start of an index in an array.


a. 0 c. 5
b. 1 d. None of the Above

_______ 4. These are the individual values in an Array.


a. Index c. Indices
b. Elements d. None of the Above

_______ 5. What is the correct way to initialize an integer array with the length of 10?
a. int num = new int[10];
b. String num[ ] = new int[10];
c. int num[] = new int[10];
d. None of the Above
PAMANTASAN NG CABUYAO |Introduction to Array 13

REFERENCES
[1] Arrays in Java from https://www.geeksforgeeks.org/arrays-in-java/
[2] Java Array Retrieved from https://www.javatpoint.com › array-in-java
[2] Java Arrays from https://www.programiz.com/java-programming/arrays
PAMANTASAN NG CABUYAO |Introduction to Array 1

Course Material No. 3

Two Dimensional
Array
Kenneth Dynielle Lawas
Course Instructor
PAMANTASAN NG CABUYAO |Introduction to Array 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Declaring Two-Dimensional Array.


• Understanding Memory representation in Array.
• Using Interactive structures and functions for Two-
dimensional Array.

RESOURCES NEEDED

For this lesson, you would need the following resources:

• Links to videos
• Links to websites
• Reference materials, tools, and equipment
PAMANTASAN NG CABUYAO |Introduction to Array 3

Before you start, try answering the following


questions. Encircle your answer:
MODULE CONTENTS

1. In Java, a 2D array can have different lengths for


each row.

TRUE or FALSE 2 Learning Lesson Title

2. 2D Array is an array of arrays

TRUE or FALSE
3 Pre-Test

3. All elements in 2D Array must be of the same


data type.
TRUE or FALSE
4 Pre-Activity Exercise

4. It is not possible to resize a 2D Array once it is


initialized.
TRUE or FALSE 5 Introduction to Array

5. The length of a row in 2D Array can be different


from the length of another row in the same array.
TRUE or FALSE 11 Activity 2

12 Group Activity

13 Summary

14 Posttest
PAMANTASAN NG CABUYAO |Introduction to Array 4

Introduction
A 2D array in Java is fundamentally an array of arrays. It is a data structure
that enables the storage of information in a grid-like format with rows and
columns. Row and column indexes uniquely identify each constituent in the
2D array.
To designate a 2D array in Java, you must specify the data type and
dimensions of the array's elements. Here is the basic syntax:.

How do we declare an Array?

For example, let's say we want to create a 2D array to store integers with 3 rows and 4 columns.
We can declare and initialize it like this:

With this declaration, a three-by-four-element array with the name myArray is created. Initially,
the array will have the default values for each element, which in this case are integer values of 0.

Another example on how to declare a 2D Array:

With this we declare a 5 by 5 element array with the name sampleArray is created. We call this
as array with declaration.
PAMANTASAN NG CABUYAO |Introduction to Array 5

Examples of Two Dimensional Array

Once again 2D arrays are created in rows and columns and each of them represents its indexes.

Example:

In our first example we call num[0][0] which has the value of 1 and num[0][1] which has the
value of 2.

Therefore we will have an output of Array num[0][0] value: 1

And Array num[0][1] value: 2.


PAMANTASAN NG CABUYAO |Introduction to Array 6

Example 2:

To iterate through a 2D array in Java we can use a for loop where in we can set the condition
base on the size of the array.

Or we can also use .length wherein it gets the size of our array.
PAMANTASAN NG CABUYAO |Introduction to Array 7

Example 3:

We can also set manually our table in 2D Array example:

Example loop when it comes to array:


PAMANTASAN NG CABUYAO |Introduction to Array 8
PAMANTASAN NG CABUYAO |Introduction to Array 9

Activity 2

Task: Imagine you are organizing a seating arrangement for a dinner party. You have a 2D
array representing the available seats, where each element represents a seat. The
value 0 represents an empty seat, and 1 represents an occupied seat. Your task is to
find an empty seat for a late-arriving guest. How would you approach this problem
using a 2D array and Java?
PAMANTASAN NG CABUYAO |Introduction to Array 10

SUMMARY

In Java, a 2D array is a data structure that allows you to store elements in a


grid-like format with rows and columns. It is essentially an array of arrays.

To declare and initialize a 2D array, you need to specify the data type of the
elements and the dimensions of the array using square brackets. For
example, int[][] array = new int[3][4]; creates a 2D array with 3 rows and 4
columns.

You can access and modify elements in a 2D array using the row and column
indices. The indices are zero-based, meaning the first row or column has an
index of 0. For example, int element = array[1][2]; retrieves the value at the
second row and third column.

2D arrays can also be jagged arrays, where each row can have a different
number of columns. This allows for flexibility in representing irregular data
structures.

KEY TERMS

2D Array for Each Loop


Row Array Length
Column Matrix
For Loop
PAMANTASAN NG CABUYAO |Introduction to Array 11

POSTTEST
Directions: Fill in the blank with the letter corresponding to your answer.

_______ 1. for(int i=0; i<10; i++). Which index holds the value of 5?
a. 1
b. 0
c. 2
d. 4

_______ 2. What is the sign of subscript in an array.

_______ 3. This number is the start of an index in an array.

_______ 4. These are the individual values in an Array.

_______ 5. What is the correct way to initialize an integer array with the length of 10?
a. int num = new int[10];
b. String num[ ] = new int[10];
c. int num[] = new int[10];
d. None of the Above
PAMANTASAN NG CABUYAO |Introduction to Array 12

REFERENCES

[1] https://docs.oracle.com/en/java/
[2] https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
[3] https://introcs.cs.princeton.edu/java/14array/
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 1

Course Material No. 4

Multidimensional Array
Part 2
Jeruz E. Claudel
Course Instructor
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Discuss the three-dimensional array;


• Understand the Input and Output Operations for Three-
Dimensional Array
• Use Interactive Structures and functions for Three-
Dimensional Array Manipulation

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 3

Before you start, try answering the following


questions.
MODULE CONTENTS
1. Defined as an array of two dimensional arrays
_______________________________________

2. This are complex for multi dimensional arrays.


_______________________________________
3 Pre-Activity Title

3. The type of data of an element of an array.


_______________________________________ 4 Pre-Activity Title

4. The name of your 3d Array


_______________________________________ 4 Three Dimensional
Array

Example of 3D Array
6 Definition

Summary
11 Key Term
References
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 4

WORD SEARCH
Find the following words in the puzzle. Words are hidden in different directions

DATATYPE
THREEDIMENSIONAL
COMPLEX
ARRAY

THREE DIMENSIONAL ARRAY

Three – dimensional array is a complex form of a multidimensional


array. A three-dimensional array can be seen as an array of two – dimensional
array for easier understanding.

• Defined as an array of two dimensional arrays.


• This are complex for multi dimensional arrays.

PURPOSE OF 3D ARRAY
Three dimensional array is useful when we want to handle a group of
elements belonging to another group. For example, suppose a college has three
departments: Electronics, Computer Science, and Information Technology.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 5

3D ARRAY DECLARATION

Declaration Syntax:

data_type[][][] array_name = new data_type[x][y][z];

For example: int[][][] arr = new int[10][20][30];

Initialization Syntax:

array_name[array_index][row_index][column_index] = value;

For example: arr[0][0][0] = 1;

3D Array with Value

datatype [] [] [] identifier={{ {v1,v2,v3},{v4,v5,v6}}};

3D Array without Value

datatype [] [] [] identifier = new datatype size[d1][d2][d3];

REMEMBER!

• d1,d2,d3 = represents the sizes of the dimensions of an array.


• Datatype = is the type of data of an element of an array.
• Identifier = is the name of your 3d Array
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 6

Example:

Example of 3d Array Definition

int [] [] [] intArray = new int[2][3][4];

• The first index represents tables/arrays. This indicates how many tables
or arrays a 3d array will have.
• The second index represent the number of Rows. It signifies the total
number of rows an array will have.
• The third index represents the number of Columns. It indicates the total
columns in the 3D Array.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 7

Example #1:

Printing the elements of the 3D Array using the for loop.

Example #2:

Printing ALL the element in a 3x2x3 Array using for loop.


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 8

Example #3:

Asking the user to input a 3x2x2 elements in the array using the scanner and printing the user input
element into a 3x2x2 table
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 9
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 10

ACTIVITY

• Write a Java program to sum values of an array.

int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


…………………………..
The sum is 55
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 11

SUMMARY

Three Dimensional Array is:

• Defined as an array of two dimensional arrays.

• This are complex for multi dimensional arrays.

• 3D arrays are defined with three brackets.

KEY TERMS

Array
3D Array
2D Array
Datatype
Identifier

POST-TEST

Directions: Identify the given statements below.

_______ 1. It is defined with single bracket.

_______ 2. It is defined with double brackets.

_______ 3. It is defined with triple brackets.

REFERENCES
[1] Arrays in Java from https://www.geeksforgeeks.org/arrays-in-java/
[2] Java Array Retrieved from https://www.javatpoint.com › array-in-java
[2] Java Arrays from https://www.programiz.com/java-programming/arrays
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 1

Course Material No. 5

Jagged Array
Jeruz E. Claudel
Course Instructor
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Discuss the three-dimensional array;


• Understand the Input and Output Operations for Three-
Dimensional Array
• Use Interactive Structures and functions for Three-
Dimensional Array Manipulation

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 3

Before you start, try answering the following


questions.
MODULE CONTENTS
1. Also known as Ragged Array
_______________________________________

2. A collection of data elements arranged in a grid-


like structure with rows and columns.
_______________________________________
3 Pre-Activity Title

3. A data structure that contains a set of elements of 4 Pre-Activity Title


the same data type.
_______________________________________

4 What is Jagged Array


In Java?

Significance of Jagged
9 Array

CRUD in Array
10
Summary
13 Key Term
References
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 4

WORD SEARCH
Scramble the provided letters to find the hidden words.

What is Jagged Array In Java?

A jagged array in Java is a collection of arrays where each array may contain a
varied number of elements. A two-dimensional array, in contrast, requires all
rows and columns to have the same length.

Jagged arrays are also known as "ragged arrays" or "irregular arrays". They can
be created by specifying the size of each array in the declaration. For example,
a jagged array with three rows can have the first row with three elements, the
second with two elements, and the third with four elements.

• They are also called as “Ragged arrays”


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 5

• In Java, it is an array of arrays where each element is an array


separately. Each element of this particular form of multidimensional
array has the special ability to have a range of sizes.

Array Recap:
• Arrays in Java are collections of similar types of elements. They are
objects, and the elements are stored in contiguous memory locations.
• Indexing of Java starts from 0 and goes up to the length of the array
minus 1 (0 to length-1).
• Arrays are stored in the heap memory.
• We have two types of Array. (Single Dimensional Array &
Multidimensional Array).

Declaration and Initialization of Jagged Array

<Data-Type> identifier [ ][ ] = new <Data-Type>[n][];

identifier[0]=new <Data-Type> [n1];


identifier[1]=new <Data-Type> [n2];

identifier[2]=new <Data-Type> [n3];

Example Syntax #1:

int arraySample[][] = new int[][]{

new int[] { 1, 2, 3, 4 },

new int[] { 4, 5},


new int[] { 6, 7, 8},

};
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 6

Example Syntax #2:

int arraySample[][] ={
new int[] { 1, 2, 3, 4 },

new int[] { 4, 5},

new int[] { 6, 7, 8},


};

Example Syntax #3:

int arraySample[][] ={
{ 1, 2, 3, 4 },

{ 4, 5},

{ 6, 7, 8},
};

Figure 5.1 Visualization of the Jagged Array


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 7

Example #1:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 8

Example #2:
Asking the user to input the size of rows and column of the Jagged Array.

Exaample #3:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 9

Significance of Jagged Array

Jagged arrays make storage easy as it provides a variable number of columns.

The performance of a program can be improved as here we don't need to store unwanted elements
and have flexibility over the number of elements in the row.
Jagged arrays have a greater speed than multidimensional arrays and single-dimensional arrays as
traversal is faster in jagged arrays.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 10

CRUD in Array

Code for Adding Elements

Code for Reading Elements


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 11

Code for Updating Elements

Code for Deleting Elements


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 12

ACTIVITY

• Write a Java program to enter the size of rows and columns of an array and ask user to
input the number of elements in each array. Print the array in a table format and print the
sum of all the elements
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 13

SUMMARY

They are also called as “Ragged arrays”

In Java, it is an array of arrays where each element is an


array separately. Each element of this particular form of
multidimensional array has the special ability to have a
range of sizes.

KEY TERMS

Jagged Array
3D Array
2D Array
Datatype
Identifier

POST-TEST

Directions: Identify the given statements below.

_______ 1. Another term for Jagged Array.

_______ 2. Two types of Arrays.

_______ 3. Two types of Arrays..

REFERENCES
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 14

[1] Arrays in Java from https://www.geeksforgeeks.org/arrays-in-java/


[2] Java Array Retrieved from https://www.javatpoint.com › array-in-java
[2] Java Arrays from https://www.programiz.com/java-programming/arrays
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 1

Course Material No. 6


Introduction to Java Swing and
the Integrated Development
Environment Walkthrough
Janus Raymond Tan
Jeruz E. Claudel
Course Instructor
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Discuss the Java Swing;


• Examines Integrated Development Environment of the
Eclipse with Java Swing; and
• An overview of how to build a Java project with a graphical
user interface (GUI).

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


• Window Builder Plugin -
https://www.eclipse.org/windowbuilder/download.php.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 3

Before you start, try answering the following


questions.
MODULE CONTENTS
1. It used to develop Graphical User Applications
(GUI), desktop-based applications
_______________________________________
Pre-Activity Title
2. It is the windows like frame and dialog boxes.
_______________________________________
3
3. It allows users to interact with electronic devices 4 Pre-Activity Title
through graphical icons
_______________________________________

4 What is Java Swing?


4. It is composed of Eclipse SWT Designer and
Eclipse Swing Designer and makes it very easy to
create Java GUI applications without spending a Installing and Using
lot of time writing code.
_______________________________________
6 Eclipse IDE and
WindowBuilder plugin

5. A platform-dependent API to develop GUI


(Graphical User Interface) or window-based
12 Java Swing
Examples
applications in Java that is insufficient for real-
world, forms-based applications. Summary
_______________________________________
15 Key Term
References
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 4

WORD SEARCH
Find the following words in the puzzle. Words are hidden in different directions

APPLICATION
ECLIPSE
JAVA SWING
USER INTERFACE
WINDOW BUILDER

WHAT IS JAVA SWING?

Window-based apps are made using Java Swing, a component of Java


Foundation Classes (JFC). The Java Swing is totally developed in Java, and it
is based on the foundation of the AWT API, which stands for Abstract
Windowing Toolkit.
Compared AWT, Java Swing offers superior platform-independent and
lightweight components.

The Swing component set was originally created because the basic
AWT components that came with the original version of the Java libraries were
insufficient for real-world, forms-based applications. All the basic components
were there, but the existing set was too small and far too restrictive. For
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 5

instance, you couldn’t even put an image on a button. To alleviate this situation,
the Swing component set offers replacements for each of the AWT
components. The Swing components support all the capabilities of the original
set and offer a whole lot more besides. As such, you should never need to deal
with any of the basic Abstract Windowing Toolkit component.
The javax.swing package offers classes for java swing API such as
JTextArea, JTextField, JButton, JRadioButton, JMenu, JColorChooser,
JCheckbox,etc.

Java Swing is used to develop Graphical User Applications (GUI),


desktop-based applications. Swing is built solely in Java and built on top of the
AWT (abstract windowing toolkit). Swing has benefits over AWT, including
that:
• Its components are lightweight and more powerful (tables, lists,
color choosers, etc.).
• It's platform-independent vs. AWT's dependence.
• It supports a better look and feel that can plug into anything.
• Here is the class hierarchy for Swing:

Figure 1 - Java Swing Class Hierarchy


from Bryce S. https://study.com/academy/lesson/java-swing-definition-classes-
methods.html

Notice that the Component class is the class that the Swing classes
inherit from. Because of the functions of the object-oriented programming, you
can call methods from the Component class in a JLabel, a JTable, or JFrame.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 6

Every components in the java swing such as the JLabel,, JList, JButton,
are from the JComponent class which can be included to the container class.
The containers are the windows that are like the frame and messageboxes or
dialog boxes. The basic swing components are known as the basic building
blocks of any Graphical User Interface (GUI) application.

What is Graphical User Interface (GUI) in Java?


GUI (Graphical User Interface) in Java is a visual experience builder
for developing Java applications. It is mostly made of graphical components
like the windows, labels, buttons etc. through which user can interact with the
application. GUI has an important role to develop an easy interfaces for the
Java applications and different applications.

Installing and Using Eclipse IDE and WindowBuilder plugin

Eclipse is an integrated development environment (IDE) for the Java


programming language as well as other programming languages like C/C++,
Python, PERL, Ruby, etc.

The Eclipse platform, which serves as the basis for the Eclipse IDE, is made up
of plug-ins and may be expanded by adding new plug-ins. The Eclipse platform
was created using Java, and it may be used to create integrated development
environments, rich application programs, and other tools. Every programming
for which a plug-in is available can be used as an IDE with Eclipse.

Requirement for Building a java swing application using the Window


builder:
Install the Eclipse IDE in your device (Laptop/Desktop).

Note : To install the Eclipse IDE, click or copy the following web site
provided below and follow the instructions for installation.
http://www.eclipse.org/downloads/
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 7

When Eclipse launches for the first time, it asks you where the workspace
folder is located. The workspace folder will house all of your data. Either
accept the default or select a different place.

Parts of the Eclipse IDE :


The main components of an eclipse window that are visible are:

• Views
• Editors (all appear in one editor area)
• Menu Bar
• Toolbar

Figure 2 – Eclipse IDE Winodw


from Tutorialspoint Website: https://www.tutorialspoint.com/eclipse/eclipse_tutorial.pdf
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 8

Download the Window Builder plugin zipped update site in


https://www.eclipse.org/windowbuilder/download.php.

Figure 2 – Window Builder Update Site


from Eclipse Foundation Website: https://www.eclipse.org/windowbuilder/download.php

What is Window Builder Plugin?


A robust and user-friendly bi-directional Java GUI builder is called
WindowBuilder. It is quite simple to construct Java GUI apps with
WindowBuilder, which is made up of SWT Designer and Swing Designer,
without having to spend a lot of time writing code. Create basic forms and
sophisticated windows using the WYSIWYG visual designer; the Java code
will be created for you. Drag-and-drop controls can be added quickly, event
handlers can be added to your controls, the properties of your controls can be
changed using a property editor, your app can be made multinational, and much
more.

Installing the Window Builder plugin In Eclipse IDE


Step 1: Once downloaded, open the Eclipse IDE and make sure all projects are
saved and closed

Step 2: On the Menu bar, select the Help menu, click the "Install new Software"
> “Add” > “Archive” button and locate your downloaded Window Builder
zipped file.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 9

Figure 3 – Installation of Window Builder plugin


from Eclipse IDE

Step 3: Check all the radio buttons shown in the figure below and select on the
radio button that says "Agree" and click on the finish button.

Figure 4 – Installation of Window Builder plugin


from Eclipse IDE
\
Step 4: Wait for the windows builder to be installed. Restart your Eclipse IDE
once the installation is complete.

Step 5: After Eclipse has been relaunched. Click on File/New/Others.


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 10

The figure below shows that the installation was successful

Creating a Sample Application using the Java Swing


Step 1 - To create a new Java project, simply click "Other". From the Select a
wizard “Window Builder > Swing Designer > JFrame” and click on the Next
button and add name for the JFrame.
Note: The steps for creating new java project, File menu > New > Other > Select
“Java Project”.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 11

Figure 5 – Creating Java Swing Application


from Eclipse IDE

Step 2 - Add a Project Name and click the Finish button.


Step 3 – In the src folder, create a new java package.

Note: File menu > New > Package is how to create a new Java package.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 12

Figure 6 – Creating a New Java Package


from Eclipse IDE

Step 4: Next, choose the package, choose the new option, click Other in the
toolbar, choose Swing Designer > JFrame, give the class a name, and press the
Finish button.
Step 5: The class is used to create an existing piece of code. Click on the
"Design tab" located at the editor's bottom to access the Window builder.

Figure 7 - Source Tab and Design Tab


from Eclipse IDE

Step 6: A panel selection window for the user interface will appear. You can
freely drag and drop the UI objects on the provided sample screen and you can
click on the "Source Tab" to alter some UI related codes.

Step 7: Simply choose the components in the palette and drag them into the
sample window to add elements like the JButton and the JTextArea to the
produced sample Java swing application.
Step 8: Absolute layout is used for this application.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 13

Right-click on the window frame, select Set Layout from the menu that appears,
then select the proper layout for the application to set the layout to "Absolute.".

Figure 8 – Setting layout into Absolute Layout


from Eclipse IDE

Step 9: On the palette toolbar, drag and drop a button and a text area onto the
JFrame. In the following screenshot, JButton and JTextArea have been selected
and adjusted the size of the elements.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 14

Figure 9 – Inserting Button and Textfield onto the Frame


from Eclipse IDE

Step 10: By simply double clicking on each element, we may edit its attributes.
This will open the source tab and place the pointer on the selected code
elements. You can modify the source code or the properties window in the left-
side corner to change things like the backdrop, background color, and font.

Note: There are two ways for handling event on the button like button clicking
events:
• Double-click the JFrame sample's elements.
• Right-click the element and choose Add Event Handler > Action >
Action Performed.
Step 11: Simply right-click the project folder in the left navigation and select
Run As > Java Application to run the sample application.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 15

Java Swing Examples

Simple Java Swing Example


A frame can be made in one of two ways:

• By constructing a Frame class object (association)


• By adding to the Frame class (inheritance)
Let's look at a straightforward swing demonstration where we create a single
button and add it to the JFrame object inside the main() function.

1) Run Eclipse IDE. Select File > New > Java Project from the menu.
2) Type the Project Name (SampleJavaProject) and leave the rest as default
values. Click Finish button at the bottom part of the window.
3) A dialog box will appear asking for module creation. In this lesson, we
will not create a module so just click “Don’t Create” button.
4) From the Project Explorer (usually at the left side of the Eclipse
window), right click on your project, in this case, SampleJavaProject >
New > Class.
5) Next step is to enter values for the creation of our Class that will contain
the main() method which serves as an entry point of our program for
execution. From the dialog box, type the name of the class (frameMain)
and put a check in public static void main(String[] args) so that the
main() method of our program will be automatically generated by
Eclipse IDE. Click the Finish button.
6) The Editor Area will automatically display the code for the class we
created (frameMain) with a given code structure for the class with its
default main() method. In the Project Explorer, you will see
frameMain.java, the java file of the class we created, saved under the
SampleJavaProject we previously created.
7) Type the following code and run the program by clicking the Run button
(CTRL+F11) in the Eclipse toolbar and observe what will happen.
8) A frame (window) with a button will appear on user’s screen upon
running the program if and only if the program does not return an error.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 16

Example of Swing by Association


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 17

Example of Swing by Inheritance

Another example of Swing Application

Figure 10 - Login Form using Java Swing


from Eclipse IDE
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 18
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 19

Figure 11 - Main Menu Example using Java Swing


from Eclipse IDE

Figure 12 - Grading System Example using Java Swing


from Eclipse IDE

Figure 13 - Basic Calculator Example using Java Swing


from Eclipse IDE
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 20

CREATING YOUR FIRST GUI APPLICATION

Task:
1. Follow the steps in installing the ECLIPSE IDE and the WINDOWBUILDER PLUGIN from above.
2. Create a new Swing Application and copy the codes below.
3. Run the code and analyze the codes below.
4. Change the Title of the JFrame into “My Example GUI Application”.
5. Change the Button into “Click Me”.
6. Add your name in the blank label.

7. Try to play with the given codes above, change the parameters, change true to false, add buttons
or labels so that you can be familiarize with the codes.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 21

SUMMARY

Java Swing is used to develop Graphical User Applications (GUI), desktop-


based applications. Swing is built solely in Java and built on top of the AWT
(abstract windowing toolkit).

GUI (Graphical User Interface) in Java is a visual experience builder for


developing Java applications. It is mostly made of graphical components like
the windows, labels, buttons etc. through which user can interact with the
application. GUI has an important role to develop an easy interfaces for the
Java applications and different applications.

KEY TERMS

Java
Java Swing
Eclipse
Graphical User Interface

POST-TEST

Directions: Identify the given statements below.

_______ 1. The code for the Java Swing Label.

_______ 2. The code for the Java Swing Frame.

_______ 3. The code for the Java Swing Button.

_______ 4. A graphical user interface (GUI) written in lightweight Java that may be used to build different
applications.

_______ 5. A graphical user interface (GUI) written in heavyweight Java that may be used to build different
applications.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 22

REFERENCES

Conrod P. & Tylee L. (2015). Learn Java™ GUI Applications A JFC Swing NetBeans Tutorial
8th Edition

Zukowski J. (2005). The Definitive Guide to Java Swing Third Edition.

Waseem M. (2022). Swing In Java : Know How To Create GUI With Examples.
https://www.edureka.co/blog/java-swing/
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 1

Course Material No. __

Working with Basic GUI


Controls Part 1
Jeruz E. Claudel
Course Instructor
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Discuss the Basic GUI Controls in Java Swing


• Differentiate and utilize JButton, JLabel and JTextField;
• Implement methods of some basic GUI components

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


• Window Builder Plugin -
https://www.eclipse.org/windowbuilder/download.php.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 3

Before you start, try answering the following


questions.
MODULE CONTENTS
___________ 1. It is is essentially a foundational
window that supports various
elements, such the menu bar,
panels, labels, text fields,
Pre-Activity Title
buttons, etc.
3
___________ 2. Digital Drawing Board
Pre-Activity Title
___________ 3. JLabel, JButton, JFrame, JPanel, 4 Commonly used Methods
of Component class
etc.

___________ 4. It shows the hierarchical


relationship between all of the 5 JFrame in Java
components in the Design View

___________ 5. Determines how an event will JPanel in Java


proceed and what actions should
be taken in its wake.
6

12 JButton in Java

16 Event Handling in Java

JLabel in Java
19

JTextField in Java
21
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 4

WORD SEARCH
Fill in the white squares with the letters, forming words with the provide
clues that may lead to the correct answer

Commonly used Methods of Component class

The methods of the Component class, which are listed below, are often
used in Java Swing.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 5

JFrame in Java

A window is shown on the screen by a top-level container known as


JFrame. A frame is essentially a foundational window that supports various
elements, such the menu bar, panels, labels, text fields, buttons, etc. Almost all
other Swing apps are launched via the JFrame window.

The user interface is constructed on an object called the frame. Every


application that we create extends the JFrame object, giving it all the properties
of a frame. The creation of Java GUI apps depends on it. Due to the fact that it
"holds" other controls, the frame is a container object. One characteristic of a
container object is that all controls will become invisible if the visible attribute
is set to false.
Frame Properties

title Frame window Title

font Font name, style, size.

background Frame background color.

foreground Color of text or graphics

x Distance from left of screen to left edge of


frame, in pixels.

y Distance from top of screen to top edge of


frame, in pixels.

width Width of frame in pixels.

height Height of frame in pixels.

resizable Boolean value indicating if frame is fixed


size or resizable

visible If false, hides the frame (and all its controls).


PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 6

How to create a JFrame via Code?


Import the following code on the top of your program:

import javax.swing.JTextFrame;

There are numerous constructors in the JFrame class that are used to
build new JFrames. You can make a JFrame using the following techniques:

CONSTUCTOR DESCRIPTION

JFrame(): By doing this, an invisible frame


can be created.

JFrame(String A frame with a title.


Title):

JFrame(Graphics creates a frame with a blank title


Configuration gc): and the screen's graphic settings

You must now provide the frame’s size and the location after
establishing the JFrame. Let's look at some possible solutions.

Java JFrame Example


1. Run Eclipse IDE. Select File > New > Java Project from the menu.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 7

2. Type the Project Name (FrameExampleProject) and leave the rest as


default values. Click Finish button at the bottom part of the window.
3. From the Project Explorer (usually at the left side of the Eclipse
window), right click on your project, in this case,
FrameExampleProject > New > Other...
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 8

4. Next step is to create our form by selecting JFrame. JFrame works like
the main window where components like panels, textfields, and buttons
are added to create a GUI. After selecting JFrame, click Next button.

5. Type the name of the JFrame. In our example, we set its name to
frameMain. Click Finish button.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 9

6. Click Design to view the JFrame and other components in the Palette.
The Design view is only available if WindowBuilder component is
installed.

Your digital drawing board is the Design View. You may change layout
settings, direct edit labels, add or delete components, and view the overall
development of your design. You may modify a component's properties in
the Property Pane by selecting it in the Design View. Moreover, this will
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 10

make the component's selection handles active. The layout properties of the
chosen control and, for some layout managers, the layout properties of
related controls, may both be changed using selection handles. The
Property Pane offers access to all the properties that may be modified in the
Design View. Row and column headers may be discernible in the header
section, depending on the layout manager in use.

7. Click contentPane in the Components window. Set the value of the


Layout property to Absolute Layout. Absolute layout will allow us to
easily set and manage the location and size of the components to put
inside our frame. Setting the layout of the contentPane (a JPanel
component on top of the JFrame) to Absolute Layout will give us the
code:

Note that when you create a JFrame object, the WindowBuilder will
automatically create a JPanel object and set its name to contentPane by default.
A JPanel is a container that allows the programmer to store component
(buttons, textfields, etc.). A class of the java.swing package that extends the
Java AWT library is the JPanel. It is renowned for being the most
straightforward type of container when developing lightweight window apps.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 11

Labels, buttons, and other panels are among the many components that are
included, and they can be combined. Most importantly, it is depicted as a
window without a title bar or border. As a result, it is essentially the most basic
container, using Flow Layout as the default layout.

In the Structure window, you can see the items which have been added
in the application window. If you click on any item, you can see the properties
of that item in the Properties window. Now if you save your changes and go to
the Source tab you will see that Eclipse has updated the source code to reflect
the changes.
The Component Tree shows the hierarchical relationship between all
of the components in the Design View. Each component in the tree shows is
icon (with potential decorators), its variable name and text label. Components
may be represented as local variables or fields, and variable names must be
unique within the scope in which the component is defined. Icon decorators are
use.
The Property Pane displays properties and events of the selected
components and provides editable text fields, lists and other controls to allow
you to edit properties and events. Select the control in the Component Tree or
on the Design View to display its properties in the Property Pane. Once visible
in the Property Pane, these values can be edited. When multiple controls are
selected, all of their shared properties are listed in the Property Pane. If not all
the selected controls have the same value for a property, the property editor in
the Property Pane will be blank.
8. Now we have created a JFrame that will be the container of our
components for our GUI.
Keep in mind that whenever we change property values of components
which are already in our JFrame, WindowBuilder is responsible for updating
its source code. At the same time, always check what specific component from
the Component Tree is selected (highlighted) whenever you change property
values to avoid confusion.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 12

JButton in Java

The class used to build a button in a JavaSE program is called JButton.


When a user clicks, hovers over, or otherwise interacts with a button, use
JButton to transmit actions to your application.
It is most likely the most popular Java GUI control. It is used to start,
stop, or interrupt a certain process.

How to create a JButton?


Import the following code on the top of your program:

import javax.swing.JButton;
A JButton can be initialized by

Constructors

Methods
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 13

Button Properties

text String displayed on button.

font Font name, style, size.

background Button background color.

foreground Color of text.

icon Picture displayed on button

If false, button is visible, but


enabled. cannot accept clicks

visible If false, hides the button

Button Methods

setText Sets the button text.

setFont Sets font name, style, size.

Sets the button background


setBackground color.

setForeground Sets color of text.


Sets boolean value to indicate
setEnabled if button is clickable or not.
Sets boolean value to indicate
setVisible if button is visible or not
Generates a click event for a
doClick button.

Java JButton Example


PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 14

Java JButton Example from the Design View

1. From the previous discussion on how to create a JFrame with its same
settings and code, click the JButton component from the Palette >
Components Category then click inside the contentPane. This will
enable the programmer to add a JButton to the contentPane (JPanel).
Note that when you add a control from the Palette to the contentPane,
the WindowBuilder will automatically provide the corresponding code
to create the added control.

2. While the JButton is selected, observe the hierarchy of components in


the Components Tree. It shows that the JButton’s variable name is
btnNewButton, same as what is displayed in the Properties Pane, and is
inside the contentPane which is a JPanel, that is why the JButton is
indented below the contentPane.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 15

3. Now Let us try to modify some properties of the JButton we created


using the Property Pane. While the JButton is selected (either through
the Components Tree or the Application View), go to the Property Pane
and scroll down to find the text property. Change the value from “New
button” to “Click Me”. Notice that in the Application View, the
JButton’s text is also changed. And by doing so, WindowBuilder
automatically modifies and generate the code for every changes you
made in a given component. The way to see the changes in the code is
to click the Source View Button beside the Design View Button.

4. Run the program by clicking the Run Menu or press CTRL+F11.


PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 16

Your output should be like the above given screenshot. If you notice,
clicking the button does not do anything since we did not capture the click
event from the user. The way we can respond to user actions is through an
ActionListener that listens to user’s actions or events.

Event Handling in Java

The mechanism known as "event handling" determines how an event will


proceed and what actions should be taken in its wake. For example, click on
button, dragging mouse etc.

Source - An item where the event takes place is its source. The source
must tell the event's handler of what happened, according to the source.
Listener - Event handler is another name for it. It is the listener's
responsibility to respond to an occurrence. The listener is an object from
the perspective of Java implementation. The listener watches for an
event before responding. When the event has been received, the listener
processes it before returning.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 17

Java Event Classes and Listener Interfaces

In order to perform Event Handling, you need to register the component with
the listener.

Java Event handling by an Anonymous Class

WindowBuilder allows programmers to easily generate code for


attaching ActionListener to listen to components’ events. Considering the
example project (ButtonExampleProject), let us modify the code so that upon
clicking the button, a DialogBox will appear using the JOptionPane Class.
Remember that this example will not discuss more about JOptionPane Class we
will have a separate discussion for this topic.

1. To add an ActionListener in the JButton (btnNewButton), go to the


Design View, select btnNewButton, either through the Components
Tree or the Application View, Right click on the button, select Add
event handler > action > actionPerformed
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 18

2. By doing so, WindowBuilder will generate a code for an Anonymous


Class under the JButton definition. Notice that in the generated code,
there is a method actionPerformed. This will be the place for us to
attach some valid Java code to respond to user’s action which is respond
to the Click Event.

3. We will try to respond to user’s action by showing a DialogBox with a


custom message using a JOptionPane Class. In our example, the
showMessageDialog() method of the JOptionPane Class accepts 2
parameters, the first one will be the parentComponent which is the
contentPane (JPanel) as the reference of the DialogBox for it to appear,
the second is the message which accepts a valid String (enclosed in
double quotes). Remember that any valid Java Statement you will put
inside the actionPerformed() method will always execute every time the
user clicks the JButton.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 19

4. Run the program using the Run Menu or by pressing CTRL+F11. The
output should be like this when you clicked the JButton.

JLabel in Java
The JLabel, which is the most basic true Swing component, is the first
to be carefully examined. The JLabel can perform a lot more tasks than the
AWT Label, which it replaces.

Text that cannot be edited directly by the user is shown using a JLabel.
A JLabel's text can be altered in reaction to events.
JLabel Constructors
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 20

JLabel Methods

How to create a JLabel?


Import the following code on the top of your program:
import javax.swing.JLabel;

JLabel Example with ActionListener

The idea behind this example to display the contents of two JLabels,
lblName for displaying “JUAN DELA CRUZ” and lblCourse for displaying
“BS INFORMATION TECHNOLOGY”. We need to use a JLabel method
named setText() which accepts a String as a parameter that sets the text to be
displayed in the JLabel. We will add a JButton that will capture the Click Event
of the user and we will put the code for setting the text of the JLabels inside the
JButton’s actioPerformed() method.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 21

JTextField in Java

A JTextField is used to show a single line of data that is either initialized


at frame creation, input by the user at runtime, or assigned by code. Text that is
being shown can be changed.

Constructors

JTextField() A constructor that generates a new


TextField

JTextField(String text) A constructor that generates a


blank text field with the given
string as its first value.

JTextField(int columns) A constructor that generates a


blank text field with the specified
columns

JTextField(String text, int A constructor that generates a


columns) blank text field with the provided
string and specified columns.

Methods

setColumns(int n) It sets the number of the columns


of the text field.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 22

setFont(Font f) It sets the font of text displayed in


the text field.

addActionListener(ActionListener It sets an ActionListener to the text


l) field.

int getColumns() It gets the number of the columns


in the textfield.

How to create a JTextField?


Import the following code on the top of your program:
import javax.swing.JTextField;

Java JTextField Example 1

The idea behind this example is to allow the user to type values for first
name and last name in the JTextFields. After entering values, the combined
values of the text entered by the user will be displayed in a JLabel following
Last Name, First Name Format upon clicking the JButton. Additionally, since
we need to capture the user’s Click Event, we will use an ActionListener for
the JButton.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 23

The above code for the JButton’s actionPerformed() method has the following
logic:

1) Get the text entered by the user from txtFirstName using the JTextField
method named getText() which returns a String (the text entered by the
user) and store temporarily in a String variable named firstName.

2) Get the text entered by the user from txtLastName using the JTextField
method named getText() which returns a String (the text entered by the
user) and store temporarily in a String variable named lastName.
3) Combine the contents of String variables lastName and firstName using +
operator to join the Strings with a “, “ in between to produce the
LastName, FirstName format and store temporarily in a String variable
named fullName.

4) Display the content of the String variable fullName in lblFullName using the
JLabel’s setText() method which accepts a String value as a parameter.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 24

LABORATORY ACTIVITY

Task:
Create a simple calculator with the basic mathematical operations that will ask the user to input two
integer number using the Window Builder designer. Provided your code below:
Program Code
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 25

SUMMARY

Java Swing is used to develop Graphical User Applications (GUI), desktop-


based applications. Swing is built solely in Java and built on top of the AWT
(abstract windowing toolkit).

GUI (Graphical User Interface) in Java is a visual experience builder for


developing Java applications. It is mostly made of graphical components like
the windows, labels, buttons etc. through which user can interact with the
application. GUI has an important role to develop an easy interfaces for the
Java applications and different applications.

KEY TERMS

Java
JLabel
JButton
JFrame
JTextField
JPanel

POST-TEST

Directions: Identify the following statements below


____________________________ 1. GUI

____________________________ 2. AWT

____________________________ 3. JFC

____________________________ 4. WYSIWYG
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 26

REFERENCES

Conrod P. & Tylee L. (2015). Learn Java™ GUI Applications A JFC Swing NetBeans Tutorial
8th Edition

Zukowski J. (2005). The Definitive Guide to Java Swing Third Edition.

Vaishnavi M R(2021). How to Create JFrame in Java? https://www.edureka.co/blog/java-jframe

Jakhotia A. (N/A). What is JPanel in Java with Examples https://www.codespeedy.com/what-is-


jpanel-in-java-with-examples/
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 1

Course Material No. 8

Working with Basic GUI


Controls Part 2
Janus Raymond Tan
Jeruz E. Claudel
Course Instructor
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Discuss the Basic GUI Controls in Java Swing


• Studies the codes and syntax of each control
• Build a simple application with Text Area, Password Field
and Option Pane.

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


• Window Builder Plugin -
https://www.eclipse.org/windowbuilder/download.php.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 3

Before you start, try answering the following


questions.
MODULE CONTENTS
1. A word or phrase that must be
used to have an admission.

2. A text field control can only


Pre-Activity Title
show a single line of text.
3
3. JTextArea, JOptionPane,
JPasswordField JTextArea in Java
4
4. A multi-line plain-text editing
control
JPasswordField in
5. A simple dialog box that either 9 Java
provides an information
message.

12 JOptionPane in Java

15 SUMMARY

15 Key Terms
Post-Test

References
17
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 4

WORD SEARCH

JTextArea in Java

JTextField's text field control can only show a single line of text. The
JTextArea is a similar control that supports several lines of text (in a single
font). This control, like the JTextField, can be used to show data that has been
initialized when the frame is built, input by a user during run-time, or assigned
by code. The text that displays can be modified.

JTextArea() It makes a new text box that is


empty.
JTextArea(String s) It generates a new text area with
the specified initial text.
JTextArea(int row, int column) It generates a new text area with
the specified number of rows and
columns is created.
JTextArea(String s, int row, int column) It generates a new text area with
the specified number of rows, and
columns, and initial text.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 5

How to create a JTextArea?


Import the following code on the top of your program:

import javax.swing.JTextArea;

Java JTextArea Example 1


PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 6

In the given example, notice that the JTextArea component was not able to
provide vertical and horizontal scrolling by default which makes the text as
highlighted below appears to be cut.

To solve the problem, we need to use a container component that will provide
the automatic vertical and horizontal scrolling within the JTextArea that will
be explained by the next example.

Java JTextArea Example 2

This example shows how to use a JTextArea component in a Swing Application


which allows a user to enter multiple lines of text with automatic vertical and
horizontal scrolling using a JScrollPane Component. Since JScrollPane is a
Container Component like JPanel, we need to first put a JScrollPane
Component in our previous example and put the JTextArea component inside
the JScrollPane specifically, in the Viewport region of the JScrollPane.

1) Select the JScrollPane Component from the Containers Category of


the Swing Designer’s Pallete.

2) Drag and release the JScrollPane Component inside the application’s


frame following the setBounds property values given in the
specification window. Since we will not programmatically modify the
JScrollPane component, it is not required to change the variable
property of the JSrollPane. We can leave the JScrollPane’s properties
to default values.

3) After placing the JScrollPane component inside the applications, frame,


you should see something like this:
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 7

The scrollPane (JScrollPane) as shown in the Components Tree should be


inside the contentPane (JPanel).

4) Now select JTextArea from the Components Category of the Swing


Designer’s Pallete and place it inside (ViewPort Region) of the
JScrollPane we created.

5) Placing the JTextArea Component inside the Viewport Region of the


JScrollPane will automatically provide vertical and horizontal scrolling
for the JTextArea. Run the program and observe what happens.

Java JTextArea Example 3


PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 8

This example demonstrates the use of a JTextArea method names void


append(String S) which is used to append the text within the method’s
parameter to the end of the JTextArea’s content. In order to not allow the user
to enter text directly to the JTextArea we will change the value of its enabled
property through the properties window to false (true by default). We will just
use a JTextField and a JButton for entering text in the JTextArea.

At the same time, in the sample execution, the first word entered in txtHobby
(JTextField) is the word “Read”. Clicking the ADD button appends the text
from the txtHobby (JTextField) to txtAHobbies.(JTextArea). This is through
adding an ActionListener in the JButton since we need to capture the user’s
click event and then adding the code for appending the text in the txtAHobbies.

We have a small issue from the given example. That is, every time we will
append a new text in txtAHobbies (JTextArea), the text will just appear at the
end of the text existing in txtAHobbies. What if we want to always append a
new text beginning with a new line to make it more presentable? The answer
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 9

is to add a “\n” or a new line character at the end of the text entered in txtHobby
(JTextField).

JPasswordField in Java
A text component designed just for entering passwords is the object of
a JPasswordField class. One line of text may be edited with it. It comes from
the class JTextField.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 10

JPasswordField() A new JPasswordField is created with a


default document, a blank beginning text
string, and a column width of 0.

JPasswordField(int It constructs a brand-new JPasswordField


columns) that is blank and has the number of
columns.

JPasswordField(String It starts a new JPasswordField with the


text) given coded text.

JPasswordField(String text, It constructs a new JPasswordField and


int columns) initialized with the provided text and
columns.

Methods of JPasswordField

char getEchoChar() The character used for echoing in


JPasswordField is returned.
setEchoChar(char c) It configures JPasswordField's echo
character.
String getPassword() It returns the text from
JPasswordField.
String getText() This function gives the
JPasswordField's password as a
string that was input. With Java 2
platform v1.2, the getPassword()
method has taken its position as the
deprecated alternative to this
method.

How to create a JPasswordField?


Import the following code on the top of your program:

import javax.swing.JPasswordField;
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 11

JPasswordField Example
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 12

JOptionPane in Java
A class called JOptionPane is used to create dialog boxes. JOptionPane
is a component of Java Swing, which is used to develop applications using
windows. JOptionPane is a Java Swing component that focused only on dialog
boxes. Any sort of dialog box may be used, including input, message, and
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 13

confirm dialog boxes. These dialog windows can be used to provide the user
information or to ask for input.

JOptionPane() It creates a JOptionPane object with


a pre-written default text message.
JOptionPane(Object message, int messageType)
It creates a JOptionPane object that
e(Object message, int messageType) will show a message with the
provided message type and user
interface-delivered default choices.
JOptionPane(Obj message) It creates a JOptionPane object that
will show a message using the User
Interface's default choices and the
plain-message message type.
JOptionPane(Object message, int It creates a JOptionPane object that
messageType, int option type) displays a message with the supplied
message type and options.
It displays a message together with
the icon, message type, and option
type that have been set.

Methods
showInputDialog It requests input from the user.

showMessageDialog The user sees a dialog window with


a message in it.
show confirm dialog A confirmation question, such as
yes/no/cancel, is asked to the user.
showOptionDialog It consists of the three things
mentioned above.

How to create a JOptionPane?


Import the following code on the top of your program:

import javax.swing.JOptionPane;

showMessageDialog()
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 14

showInputDialog()

showConfirmDialog()
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 15

SIMPLE LOGIN APPLICATION ACTIVITY

1. Create a simple login application program where a user will enter his name and password. The
application will then preview the username in a message dialog. Be creative with the design by
changing the properties of each components

Screen record your code and output and send it to our LMS
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 16

SUMMARY

Just one line of text may be displayed in the text field control of JTextField. A
comparable control that accommodates many lines of text is the JTextArea (in
a single font). You can change the wording that appears on screen.

The object of a JPasswordField class is a text field intended just for password
entry. It allows for editing of one line of text. It is derived from the JTextField
class.

It makes it easier to create dialog boxes because JOptionPane is a component


of Java Swing. It offers common dialog boxes including the message dialog
box, input dialog box, and confirm dialog box.

KEY TERMS

Java
Java Swing
JTextArea
JPasswordField
JOptionPane

POST-TEST

Directions: INSERT POST-TEST ACTIVITY HERE.

1. Password field code

2. A message dialog box that asks


for input
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 17

• 3. List all the JOptionPane dialog


boxes

REFERENCES

Conrod P. & Tylee L. (2015). Learn Java™ GUI Applications A JFC Swing NetBeans Tutorial
8th Edition

Zukowski J. (2005). The Definitive Guide to Java Swing Third Edition.

Vaishnavi M R(2021). How to Create JFrame in Java? https://www.edureka.co/blog/java-jframe

Jakhotia A. (N/A). What is JPanel in Java with Examples https://www.codespeedy.com/what-is-


jpanel-in-java-with-examples/
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 1

Course Material No. 9

Working with Basic GUI


Controls Part 3
Janus Raymond Tan
Jeruz E. Claudel
Course Instructor
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Discuss the Basic GUI Controls in Java Swing


• Studies the codes and syntax of each control
• Build a simple application with Checkbox and Radio Button.

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


• Window Builder Plugin -
https://www.eclipse.org/windowbuilder/download.php.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 3

Before you start, try answering the following


questions.
MODULE CONTENTS
1. A class in JAVA may be used as
a toggle to switch off or on any
feature.
Pre-Activity Title
2. adds item listener to the
component
3
3. returns the checkbox's text
4 JCheckbox in Java
4. puts the provided text as the
component’s text

5. A radio button java swing code. 10 JRadioButton in Java

Summary
15 Key Terms

16 Reference
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 4

WORD SCRAMBLE
Scramble the letters and provide the correct answer on the blank spaces
below.

JCheckbox in Java

The JCheckBox class in JAVA may be used as a toggle to switch off or


on any feature. This class essentially produced a checkbox with two options:
on and off.
JCheckBox has two options: chosen and deselected. It informs the user
of its status. JCheckBox is a checkbox implementation. JCheckBox inherits the
class of JToggleButton.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 5

Methods

addActionListener(ItemListener l): adds item listener to the component


itemStateChanged(ItemEvent e) abstract function executed when the
state of the object to which listener is
assigned changes
getItem() : Gives the component-specific object
connected to the item whose status
changed back.
getStateChange() : returns the item's new state.
SELECTED and DESELECTED are
the two states that the ItemEvent
class defines.
getSource() : returns the element from which the
item event was fired.

How to create a JCheckbox?

Import the following code on the top of your program:

import javax.swing.JCheckbox;
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 6

Example 1
This example shows how to use a JCheckBox component in a Swing
Application which allows a user to check or uncheck the JCheckBoxes

In the given example, notice that the even without the code for the click
event in the JCheckBoxes, the program was able to show the appearance of
checking and unchecking the JCheckBoxes. Event Listener is not needed by
default if you want to show the process of toggling the JCheckBoxes

Example 2

This example shows how to use a JCheckBox component in a Swing


Application which allows a user to check or uncheck the JCheckBoxes.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 7

ItemListeners are added in two JCheckBoxes to listen to item events for us to


get the state (1 = checked, 2 = unchecked) of the JCheckBoxes whenever the
user clicks the JCheckBoxes. We added a JLabel component named “lblResult”
to display the status of the JCheckBoxes.

By adding an ItemListener in each JCheckBoxes, we are able to get


their state as what is defined inside the default itemStateChanged(ItemEvent
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 8

e) method. The “e” from the method parameter allows us to access the
getStateChange() method of the ItemEvent Class which returns 1 if the status
of the JCheckBox is checked, 2 if unchecked. By using a ternary operator (?),
we are able to conditionally check the value returned by the getStateChange()
method and return the Strings “Checked” and “Uncheked” in one single line
including the lblResult.setText() method.

Example 3

This example shows how to use multiple JCheckBox components in a


Swing Application which allows a user to check or uncheck the JCheckBoxes.
The idea is to show in a Message Dialog all selected checkboxes upon clicking
the SHOW Button.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 9
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 10

JRadioButton in Java

A radio button is made using the JRadioButton class. It is employed to


select one alternative from a variety of possibilities. It is frequently utilized in
test or quiz systems.

Typically, a set of radio buttons is made to provide the user alternatives,


but only one option may be chosen at once.

JRadioButton() creates a radio button with no text.

JRadioButton(String s) creates a radio button with the


provided text

JRadioButton(String s, boolean selected) Creates a radio button with the


provided text and selected state.

Methods

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void It is used to add the action listener to this object.


addActionListener(ActionListener
a)

How to create a JRadioButton?

Import the following code on the top of your program:


import javax.swing.JRadioButton;
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 11

Example

This example shows how to use a JRadioButton component in a Swing Application which allows
a user to select or unselect the JRadioButtons. A ButtonGroup class is used so that only one single
radio button can be selected at a time and this is the difference of JRadioButton from JCheckBox
components. If in case you will need to create more than one radio button group for selection, lets
us say, one button group for the SEX selection, another for CIVIL STATUS selection, then two
separate ButtonGroup objects will needed.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 12

Make sure that the javax.swing.ButtonGroup is imported on top of the code to avoid errors in
creating a new ButtonGroup object.
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 13

INSERT SHORT ACTIVITY HERE

Create a simple pizza menu option using the JRadioButton and JCheckBox. Add a button that
will show if no order has been created or will show the summary of your order in a Message Dialogbox.

Example Output:
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 14

SUMMARY
JCheckBox has two options: chosen and deselected. It informs the user of its
status. JCheckBox is a checkbox implementation. JCheckBox inherits the
class of JToggleButton.

A radio button is made using the JRadioButton class. It is employed to select


one alternative from a variety of possibilities. It is frequently utilized in test or
quiz systems.

KEY TERMS

Java
Java Swing
JCheckbox
JRadioButton

POST-TEST

Directions: In the space provided, write TRUE the statement is correct, otherwise write FALSE.

1. Button group is used to group all


checkbox

2. JRadioButton is used to select


one alternative from a variety of
choices

3. JCheckbox has two options:


Selected and Deselected
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE 15

REFERENCES

Conrod P. & Tylee L. (2015). Learn Java™ GUI Applications A JFC Swing NetBeans Tutorial
8th Edition

Javatpoint, “Java JCheckBox”. https://www.javatpoint.com/java-jcheckbox.

Javatpoint, “Java JRadioButton”. https://www.javatpoint.com/java-jradiobutton.

Tutorialspoint, “What are the differences between JRadioButton and JCheckBox in Java?”

Zukowski J. (2005). The Definitive Guide to Java Swing Third Edition.


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 1

Course Material No. 13

Working With Advanced GUI


Controls Part 1
Janus Raymond Tan
Jeruz E. Claudel
Mark Anthony J. Esmeralda
Course Instructor
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 2

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

Discuss JComboBox Class towards creating, building


and applying Swing Application
Understand commonly used constructors and methods in
creating a JList object
Apply commonly used constructors and methods in
creating a JScrollBar object towards building a Swing
Application;

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

Eclipse IDE - http://www.eclipse.org/downloads/


Window Builder Plugin -
https://www.eclipse.org/windowbuilder/download.php
.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Before you start, try answering the following


questions.
MODULE CONTENTS
1. It used to create a component that displays
drop-down lists and has an editable field.

Pre-Activity Title
2. It is used to create a swing component that 3
displays a list of objects that allows user
to represent list of items.
What is JComboBox?
4
3. It is used to create a vertical and horizontal
scrollbar of a swing component. 28 What is JList?

4. It is an ordered collection interface that provides 41 What is JScrollBar?


control over the position in which you can add an
element using index.

48 Pos-Test

5. It is used to handle user interaction whenever


the users move the scrollbar Summary
49 Key Term
References
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

WORD SEARCH
Find the following words in the puzzle. Words are hidden in different directions

JCOMBOX
JLIST
JSCROLLBAR
USER INTERFACE
OBJECT

WHAT IS JComboBox?

JComboBox is one of the advanced component GUI controls available


in Swing API. You can create combo boxes in Java and this displays a popup
menu which allows the user to select a value from a drop-down list and a text
field. If the text-field section of the control is editable, the user can update a
value that was taken from the drop-down list or put a new value in the field.

If you make the combo box editable, then the combo box includes an
editable field into which the user can type a value depending on the choice of
the programmer.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Figure 1 - Java JComboBox Example


from https://www.javatpoint.com/java-jcombobox

JComboBox class declaration

This is the declaration for javax.swing.JComboBox class.

The following are the commonly used constructors of the JComboBox:

Table 1 - Commonly used Constructors Example


from https://www.javatpoint.com/java-jcombobox

The following are the commonly used methods of the JComboBox:

Table 2 - Commonly used Methods Example


from https://www.javatpoint.com/java-jcombobox
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

JComboBox Examples

Java JComboBox Example 1:

The example given below shows how to use a JComboBox component


in a Swing Application which allows a user to select among the list of items
available in the JComboBox. While adding items is done through the program
code, one line of code per item.

Sample output upon clicking the JComboBox:

cboCountries

contentPane

Specifications of the JComboBox:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JComboBox Specifications
Property Value
Variable cboCountries
X-axis location 174
Bounds Y-axis location 13
Width 126
Height 31
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JComboBox Program Code: 10

Note: Every declaration in our JComboBox, we defined Object as the type of


data to be used by the items defined inside the cboCountries which means that
the items are all considered Object Types.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Java JComboBox Example 2: GE
10

This example shows how to use a JComboBox component in a Swing


Application which allows a user to select among the list of items available in
the JComboBox. This time, we will use the constructor of the JComboBox
which accepts an array of objects as its parameter. In our case, we will define
an Array of Strings for the list of countries as the parameter of the
JComboBox(Object[] items) constructor. The output of the program code given
will be the same as with Example 1.

Sample output upon clicking the JComboBox:

cboCountries

contentPane

Specifications of the JComboBox:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JComboBox Specifications
Property Value
Variable cboCountries
X-axis location 174
Bounds Y-axis location 13
Width 126
Height 31
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
Java JComboBox Program Code:

Note: This example simplifies the way on how to put items inside the
JComboBox. We first define an Array of Strings named countries that
will hold the items for {“USA”, “PH”, “AUS”, “CAN”, “IND”}. By
doing this, we can easily identify each item through index values
(starting from 0). And by simply adding the Array of Strings to the
constructor of the JComboBox, it will be automatically available for
selection upon running the program.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JComboBox Example 3: 10

This example shows how to use some JComboBox


component methods to retrieve the index of the item (starts with 0)
and the item itself being selected by the user to be displayed in a
MessageDialog upon clicking a SHOW button.

Sample output upon clicking the JComboBox:

cboCountries

btnShow

contentPane

First MessageDialog to be displayed shows the


currently selected item.

Second MessageDialog to be displayed shows the


index number of the item currently selected. In this
example, 2 is the index number shown since AUS is
the 3rd item in the Array of Strings (refer to the
code).

Third MessageDialog to be displayed shows the


item currently selected using the getItemAt(index)
method used to retrieve an item in the list by
specifying a valid index number.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Specifications of the JComboBox: 10

JPanel
Specifications
Property Value
Variable contentPane
Layout absolute

JComboBox
Specifications
Property Value
Variable cboCountries
X-axis location 174
Bounds Y-axis location 13
Width 126
Height 31

JButton Specifications
Property Value
Variable btnShow
X-axis location 112
Bounds Y-axis location 95
Width 85
Height 21
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JComboBox Program Code: 10

Java JComboBox Example 4:

This example shows how to use some JComboBox


component method to retrieve the item being selected by the user to
be displayed in a JLabel every time the user selects an item in the
JComboBox. This time, we will add an ItemListener in the
JComboBox to listen to item state changes. Instead of adding a button
to trigger the event, we will automatically display the complete name
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
of the abbreviated country name in the JLabel. For example, if the 10
user selects “USA”, we will display “United States of America”.

Sample output upon selecting 3rd item from the JComboBox:

cboCountries

lblCoun
try

contentPane

Specifications of the JComboBox:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JComboBox Specifications
Property Value
Variable cboCountries
X-axis location 174
Bounds Y-axis location 13
Width 126
Height 31

JLabel Specifications
Property Value
Variable lblCountry
Text
X-axis location 20
Bounds Y-axis location 97
Width 280
Height 31
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JComboBox Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Note: You can also change the previous code for identifying the 10
currently selected item by using the getSelectedIndex() method
instead of using the getSelectedItem() method. The use of the
getSelectedIndex() method is much safer because he condition will
be based on the index number of the currently selected item therefore
eliminating the comparison of Strings in the if condition. Consider
the updated code below:

Java JComboBox Example 5:

This example shows how to use a JComboBox component


method to set the currently selected item based on the programmer’s
choice upon running the program.

Sample output upon selecting 3rd item from the JComboBox:

cboCountries

lblCountry

contentPanE
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Specifications of the JComboBox: 10

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JComboBox Specifications
Property Value
Variable cboCountries
X-axis location 174
Bounds Y-axis location 13
Width 126
Height 31

JLabel Specifications
Property Value
Variable lblCountry
Text
X-axis location 20
Bounds Y-axis location 97
Width 280
Height 31
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JComboBox Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Note: The setSelectedIndex() method is used to set the


currently selected item based on a valid index. By default, without
setting the index, 0 is the selected index which sets the first item in
the list as the default item shown in the JComboBox. Try to change
the selected index to -1.

Then the output will be,

By setting the selected index to -1, no item will be displayed in the


JComboBox by default.

Java JComboBox Example 6:

This example shows how to dynamically add new items in the


JComboBox component using a JTextField and a JButton.
Additionally, a JLabel is used to display the number of items in the
list of JComboBox and automatically updates the value whenever the
user adds a new item.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Sample output upon entering a text in the JTextField: 10

cboCountries

txtNewCountry

btnAdd
contentPane
lblItemCount

Sample output upon entering a text in the JTextField:

Newly added item (“ITA”) is


immediately available in the list and
at the same time, the item count
displayed in the JLabel is
automatically updated.

Specifications of the JComboBox:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JComboBox Specifications
Property Value
Variable cboCountries
X-axis location 174
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Y-axis location 13 10
Bounds Width 162
Height 31

JTextField Specifications
Property Value
Variable txtNewCountry
Text
X-axis location 204
Bounds Y-axis location 72
Width 132
Height 34

JButton Specifications
Property Value
Variable btnAdd
Text ADD
X-axis location 137
Bounds Y-axis location 120
Width 85
Height 31

JLabel Specifications
Property Value
Variable lblItemCount
Text Item Count :
X-axis location 89
Bounds Y-axis location 188
Width 178
Height 13
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JComboBox Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Java JComboBox Example 6:

This example shows how to remove an item or remove all


items in the JComboBox component using some JComboBox
component methods.

Sample output upon selecting the 3rd item in the JComboBox:

btnRemoveSelectedItem btnRemoveAllItems
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Sample output after clicking the REMOVE SELECTED ITEM 10
BUTTON while the 3rd item in the JComboBox is selected:

Note: Notice that the 3rd item from the list (“AUS”) is immediately
deleted after clicking the REMOVE SELECTED ITEM Button. At
the same time, the item count displayed is updated.

Sample output after clicking the REMOVE ALL ITEMS BUTTON:

Note: By clicking the REMOVE ALL ITEMS Button, all items in


the JComboBox is now cleared and at the same time, the item count
displayed is updated and shows 0 as the value of item count.

Specifications of the JComboBox:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

JComboBox Specifications
Property Value
Variable cboCountries
X-axis location 174
Bounds Y-axis location 13
Width 162
Height 31

JTextField Specifications
Property Value
Variable txtNewCountry
Text
X-axis location 204
Bounds Y-axis location 72
Width 132
Height 34

JButton Specifications
Property Value
Variable btnAdd
Text ADD
X-axis location 137
Bounds Y-axis location 120
Width 85
Height 31

JLabel Specifications
Property Value
Variable lblItemCount
Text Item Count :
X-axis location 89
Bounds Y-axis location 188
Width 178
Height 13

JButton Specifications
Property Value
Variable btnRemoveSelectedItem
Text REMOVE SELECTED ITEM
X-axis location 378
Bounds Y-axis location 13
Width 234
Height 31
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
JButton Specifications 10
Property Value
Variable btnRemoveAllItems
Text REMOVE ALL ITEMS
X-axis location 378
Bounds Y-axis location 72
Width 234
Height 31
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JComboBox Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
WHAT IS JList?

A component of the class JList shows a list of objects and


allows the user to select one or more of them. The list's contents are
maintained by a different model called ListModel.

JList class declaration

This is the declaration for javax.swing.JList class .

The following are the commonly used constructors of the JList:

The following are the commonly used methods of the JList:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

JList Examples

Java JList Example 1:

This example shows how to use a JList component in a Swing


Application which allows a user to select among the list of items
available in the JList. In this example, item selection is single
selection so that users are not allowed to select multiple items at the
same time. Additionally, selecting an item will not trigger any
command in the program it will just show the highlighted item as the
currently selected item from the list. Adding of items is done through
the program code, one line of code per item using a ListModel that
will maintain the contents of the JList. Unlike the JComboBox Class,
JList Class does not have built-in methods to directly add items in the
list. Instead, we need to use a DefaultListModel Object that will
serve as data storage reference of our JList. In order to use the
DefaultListModel in the program, you need to import its
corresponding class library at the top of your code as shown below:

import javax.swing.DefaultListModel;

Sample output clicking the second item from the JList:

listFruits

contentPane

lblItemCount
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Specifications of the JList: 10

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JList Specifications
Property Value
Variable listFruits
selectionMode SINGLE_SELECTION
X-axis location 132
Bounds Y-axis location 20
Width 172
Height 79

JLabel Specifications
Property Value
Variable lblItemCount
Text
X-axis location 105
Bounds Y-axis location 120
Width 218
Height 21
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JList Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Java JList Example 2:

This example shows how to use a JList Component in a Swing


Application which allows a user to select among the list of items
available in the JList. This time, we will add a JButton that will be
used to trigger an event to show the selected (highlighted) item in the
JList through a MessageDialog.

Sample output upon clicking the SHOW button while the “Orange”
item is selected.

btnShow

Specifications of the JList:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JList Specifications
Property Value
Variable listFruits
selectionMode SINGLE_SELECTION
X-axis location 132
Bounds Y-axis location 20
Width 172
Height 79

JLabel Specifications
Property Value
Variable lblItemCount
Text
X-axis location 105
Bounds Y-axis location 120
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Width 218 10
Height 21

JButton Specifications
Property Value
Variable btnShow
Text SHOW
X-axis location 172
Bounds Y-axis location 161
Width 85
Height 21

JButton Specifications
Property Value
Variable btnShow
Text SHOW
X-axis location 172
Bounds Y-axis location 161
Width 85
Height 21

Java JList Program Code:

Note: Add the given lines of code to provide functionality for the
SHOW Button. The getElementAt(int index) is a built in method of
the ListModel used to retrieve an element in the model using a valid
index position. Since in this example we need to retrieve the currently
selected (highlighted) item from the JList, we get the index of the
currently selected item in the JList using the getSelectedIndex()
method which returns the valid index of the currently selected item
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
in the JList (returns 2 since “Orange” is the the 3rd position within 10
the list).

Java JList Example 3:

This example demonstrates how to dynamically add new


items in the JList using an addElement() method of the ListModel. A
TextField will be used to accept input from the user and every time
the user inputs new item, the JLabel for displaying the number of
items in the ListModel will also be updated. And to allow horizontal
and vertical scrolling, we will add a JScrollPane as the container
element of the JList added through the JScrollPane’s ViewPort.

Sample output upon adding 4 new items in the JList using the ListModel.

Specifications of the JList:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JScrollPane Specifications
Property Value
Variable scrollPane
X-axis location 219
Bounds Y-axis location 23
Width 190
Height 198
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
JList Specifications
Property Value
Variable listFruits
selectionMode SINGLE_SELECTION

JLabel Specifications
Property Value
Variable lblItemCount
Text
X-axis location 219
Bounds Y-axis location 161
Width 191
Height 21

JButton Specifications
Property Value
Variable btnAdd
Text ADD
X-axis location 10
Bounds Y-axis location 85
Width 85
Height 28

JButton Specifications
Property Value
Variable btnShow
Text SHOW
X-axis location 125
Bounds Y-axis location 85
Width 85
Height 28
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JList Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Note: Modify the code to include a REMOVE Button using the GE
10
removeElementAt(int index) method of the ListModel to remove the currently
selected item from the JList. Additionally, update the number of items
displayed in the JLabel every time the user clicks the REMOVE Button.

Java JList Example 4:

This example demonstrates allowing multiple selection of items from


the JList at the same time retrieving the selected items to be displayed in a
MessageDialog after clicking the SHOW Button.

Sample output upon clicking the SHOW Button while multiple items are
selected:

Specifications of the JList:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JScrollPane Specifications
Property Value
Variable scrollPane
X-axis location 219
Bounds Y-axis location 23
Width 190
Height 198

JList Specifications
Property Value
Variable listFruits
selectionMode MULTIPLE_INTERVAL_SELEC
TION
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
JLabel Specifications GE
Property Value 10
Variable lblItemCount
Text
X-axis location 219
Bounds Y-axis location 161
Width 191
Height 21

JButton Specifications
Property Value
Variable btnAdd
Text ADD
X-axis location 10
Bounds Y-axis location 85
Width 85
Height 28

JButton Specifications
Property Value
Variable btnShow
Text SHOW
X-axis location 125
Bounds Y-axis location 85
Width 85
Height 28
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Java JList Program Code: GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Note: Modify the code to include a REMOVE MULTIPLE Button using the
removeElementAt(int index) method of the ListModel to remove the all items
selected from the JList in a single click. Additionally, update the number of
items displayed in the JLabel every time the user clicks the REMOVE
MULTIPLE Button.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
WHAT IS JScrollBar?

A horizontal and vertical scrollbar can be made with JScrollBar. A


component like JPanel or a top-level container like JFrame can both accept the
addition of a JScrollBar and it is a compact component that extends the
JComponent class.

We are only given a non-functional scrollbar that does not


automatically scroll across the display when we create an object of type
JScrollBar.

JScrollBar class declaration

This is the declaration for javax.swing.JScrollBar class.

The following are the commonly used constructors of the JScrollBar:

JScrollBar Examples

Java JScrollBar Example 1:

This example shows how to use a JScrollBar component in a Swing


Application which allows a user to increase or decrease the values of both
horizontal and vertical scrollbar. An addAdjustmentListener() is used to listen
to user actions every time the user adjusts the scrollbars. By using an
adjustmentValueChanged() of the addAdjustmentListener(), we will be able to
show in two separate JLabels the values of the scrollbars.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Sample output upon adjusting the values of both ScrollBars: 10

scrollBarVertical

scrollBarHorizontal

lblScrollBarVertical

lblScrollBarHorizontal

contentPane

Specifications of the JScrollBar:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JScrollBar Specifications
Property Value
Variable scrollBarVertical
X-axis location 93
Bounds Y-axis location 20
Width 31
Height 124
maximum 100
minimum 0
orientation VERTICAL

JScrollBar Specifications
Property Value
Variable scrollBarHorizontal
X-axis location 231
Bounds Y-axis location 72
Width 195
Height 29
maximum 100
minimum 0
orientation HORIZONTAL
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
JLabel Specifications GE
Property Value 10
Variable lblScrollBarVertical
Text
X-axis location 21
Bounds Y-axis location 179
Width 185
Height 23

JLabel Specifications
Property Value
Variable lblScrollBarHorizontal
Text
X-axis location 241
Bounds Y-axis location 179
Width 185
Height 23
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JList Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

CREATING YOUR JAVA JSCROLLBAR WITH ADJUSTMENTLISTENER

Task:
1. Create a vertical and horizontal scrollbar. The position of the slider will be updated whenever the
position of the slider changed.
2. Create a new Swing Application and copy the codes below.
3. Run the code and analyze the codes below.
4. Change the Title of the JScrollBar into “This is ScrollBar”.
5. Change the value of the label.setSize into 450,150.
6. Add your name in the blank label.

import javax.swing.*;

import java.awt.event.*;

class ScrollBarExample

ScrollBarExample(){

JFrame f= new JFrame("Scrollbar Example");

final JLabel label = new JLabel();

label.setHorizontalAlignment(JLabel.CENTER);

label.setSize(400,100);

final JScrollBar s=new JScrollBar();

s.setBounds(100,100, 50,100);

f.add(s); f.add(label);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

s.addAdjustmentListener(new AdjustmentListener() {

public void adjustmentValueChanged(AdjustmentEvent e) {

label.setText("Vertical Scrollbar value is:"+ s.getValue());

});

public static void main(String args[])

new ScrollBarExample();

}}
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
SUMMARY

JScrollbar class is used to add horizontal and vertical scrollbar. It is an


implementation of a scrollbar and it inherits JComponent class.

JList class represents a list of text items. The list of text items can be set up
so that the user can choose either one item or multiple items. It inherits
JComponent class.

JComboBox is the object of Choice class that is used to show popup menu of
choices. Choice selected by user is shown on the top of a menu. It inherits
JComponent class.

KEY TERMS

Java

JComboBox

JList

JScrollBar

Object

Graphical User Interface

POST-TEST

Directions: Identify the given statements below.

1. Creates a vertical scrollbar with the initial values.

2. Creates a scrollbar with the specified orientation and the initial values.

3. Creates a JList with an empty, read-only, model.

4. Creates a JComboBox with a default data model.

5. It is used to add an item to the item list.


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
REFERENCES

Conrod P. & Tylee L. (2015). Learn Java™ GUI Applications A JFC Swing NetBeans Tutorial
8th Edition

Zukowski J. (2005). The Definitive Guide to Java Swing Third Edition.

Waseem M. (2022). Swing In Java : Know How To Create GUI With Examples.
https://www.edureka.co/blog/java-swing/
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 1

Course Material No. 14


WORKING WITH ADVANCED GUI
CONTROLS PART 2
Janus Raymond Tan
Jeruz E. Claudel
Mark Anthony J. Esmeralda
Course Instructor
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 2

14

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Understand JTable and JScrollPane Class towards building a Swing Application

• Apply commonly used constructors and methods in creating a JTable object

• Apply commonly used constructors and methods in creating a JScrollPane object

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


• For further API reference and developer documentation, see Java SE Documentation.
• Window Builder Plugin -
https://www.eclipse.org/windowbuilder/download.php.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Before you start, try answering the following


questions.
MODULE CONTENTS
1. It used to create tables using data shown in
several rows and columns and similar to
database or spreadsheet.

Pre-Activity Title
3
2. It is used to create a swing component that
provides a scrollable view in java.
What is JTable?
4
3. It is used to create an empty cell table that is
created and initialized with the default data 5 Examples of JTable
model.

19 What is JScrollPane?
4. It is used to create a scroll pane with the specified
component.

21 Pos-Test

5. It is used to creates a scroll pane with the


specified scroll policy. Summary
22 Key Term
References
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

WORD SCRAMBLE
Scramble the letters and provide the correct answer on the blank spaces below.

BTLEAJ
SORLJNLEPAC
ATELB
OBUNTT
NENPOCOTM

WHAT IS JTable?

The JTable is used to display and edit regular two-dimensional tables


of cells. The JTable has many facilities that make it possible to customize its
rendering and editing but provides defaults for these features so that simple
tables can be set up easily.

The JTable class is a part of Java Swing Package and is generally used
to display or edit two-dimensional data that is having both rows and columns.
It is similar to a spreadsheet. This arranges data in a tabular form.

The JTable class is used to display data in tabular form. It is composed


of rows and columns.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
The following are the commonly used constructors of the JTable: 10

Figure 1 - Commonly used Constructors Example


from https://www.javatpoint.com/java-jtable

The following are the commonly used methods of the JTable:

Figure 2 - Commonly used Methods Example


from https://www.javatpoint.com/java-jtable

JTable Examples

Java JTable Example 1:

The example shows how to use a JTable component in a Swing


Application which displays a 6 x 4 table (6 rows and 4 columns) containing
data for columns such as ID, LAST NAME, FIRST NAME and COURSE. The
use of the constructor of the JTable which accepts a two-dimensional array for
the rows that will represent the data, and a one-dimensional array for the
columns that will represent the column names is used in this example. At the
same time, a JScrollPane will be used to provide vertical and horizontal scroll
functionality to the table as well as to make the column headers appear at the
top of the table. Additionally, the number of rows in the table is displayed in a
JLabel below the table.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon loading the frame: GE
10

contentPane
scrollPane
tblStudent

lblRowCount

Specifications of the JTable:

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JScrollPane Specifications
Property Value
Variable scrollPane
X-axis location 25
Bounds Y-axis location 29
Width 387
Height 89

JTable Specifications
Property Value
Variable tblStudent

JLabel Specifications
Property Value
Variable lblRowCount
Text
X-axis location 298
Bounds Y-axis location 128
Width 114
Height 17
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JTable Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Note: In the given example, notice that the JScrollPane automatically adds a
vertical scrollbar depending on the size of the JScrollPane (if it can display all
the contents by default) and the number of rows from the array of data.

Java JTable Example 2:

This example shows how to use a JTable Component in a Swing


Application that will demonstrate a simple CRUD (CREATE, READ,
UPDATE and Delete) Application.

The DefaultTableModel Class is used in this example as the way to


handle the operations for creating, reading, updating and deleting records that
is being displayed in the JTable being a class having methods for adding a new
row in the model (addRow()), updating values in a selected row in the JTable
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
(setValueAt()), and removing a selected row in the JTable (removeRow()). GE
10

Sample output upon entering values in txtName and txtAge while performing
the NEW BUTTON operation:

Sample output upon clicking the SAVE BUTTON while performing NEW
BUTTON Operation:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon selecting a row in tblPersonalInfo while performing the GE
10
UPDATE BUTTON operation:

Sample output upon changing the content of txtName and txtAge while
performing the UPDATE BUTTON operation:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon clicking the SAVE BUTTON while performing UPDATE GE
10
BUTTON Operation:

Sample output upon clicking the SAVE BUTTON while performing DELETE
BUTTON Operation:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Specifications of the JTable: 10
JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JLabel Specifications
Property Value
Variable lblId
Text
X-axis location 124
Bounds Y-axis location 33
Width 46
Height 13

JTextField Specifications
Property Value
Variable txtName
Text
X-axis location 125
Bounds Y-axis location 66
Width 395
Height 19

JTextField Specifications
Property Value
Variable txtAge
Text
X-axis location 125
Bounds Y-axis location 95
Width 96
Height 19

JScrollPane Specifications
Property Value
Variable scrollPane
X-axis location 30
Bounds Y-axis location 154
Width 490
Height 210

JTable Specifications
Property Value
Variable tblPersonalInfo

JLabel Specifications
Property Value
Variable lblRecordCount
Text
X-axis location 417
Bounds Y-axis location 374
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
Width 103 PA
Height 13 GE
10
JButton Specifications
Property Value
Variable btnNew
Text NEW
X-axis location 30
Bounds Y-axis location 393
Width 85
Height 21

JButton Specifications
Property Value
Variable btnUpdate
Text UPDATE
X-axis location 30
Bounds Y-axis location 422
Width 85
Height 21

JButton Specifications
Property Value
Variable btnDelete
Text DELETE
X-axis location 30
Bounds Y-axis location 449
Width 85
Height 21

JButton Specifications
Property Value
Variable btnSave
Text SAVE
X-axis location 153
Bounds Y-axis location 393
Width 85
Height 21

JButton Specifications
Property Value
Variable btnCancel
Text SAVE
X-axis location 153
Bounds Y-axis location 422
Width 85
Height 21
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JTable Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Note: Try to modify the code so that the program should be more user-friendly 10
by not allowing the user to click NEW, UPDATE, and DELETE Button when
the user is currently in the process of performing a selected operation. Only the
SAVE and CANCEL Button should be enabled if the user is not yet done in a
particular operation. Additionally, consider disabling the txtName and txtAge
while the user is in the DELETE operation.

WHAT IS JScrollPane?

A JscrollPane is used to make scrollable view of a component. When


screen size is limited, we use a scroll pane to display a large component or a
component whose size can change dynamically.

The following are the commonly used constructors of the JScrollPane:

The following are the commonly used methods of the JScrollPane:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

JScrollPane Example

Java JScrollPane Example :

See the Example 2 of the JTable as an example application of the


JScrollPane.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

CREATING YOUR JAVA JTABLE WITH JSCROLLPANE

Task:
1. Create a JScrollPane with JTable displaying the Top 10 Countries with Most Forested Area. Your table
must include Rank, County, and Forested Area (km sq). Any values are acceptable in the table.

Example Output:

2. Try to play with the given codes above, change the parameters, change true to false, setSize and
BorderLayout so that you can be familiarize with the codes.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
SUMMARY

The JTable is used to display and edit regular two-dimensional tables of cells.
The JTable has many facilities that make it possible to customize its rendering
and editing but provides defaults for these features so that simple tables can
be set up easily.

A JScrollPane manages a viewport, optional vertical and horizontal scroll


bars, and optional row and column heading viewports. You can find task-
oriented documentation of JScrollPane in How to Use Scroll Panes, a section
in The Java Tutorial. Note that JScrollPane does not support heavyweight
components.

KEY TERMS

JTable

JScrollPane

contentPane

DefaultTableModel Class

JLabel

addColumns()

POST-TEST

Directions: Identify the given statements below.

1. Creates a scroll pane with a component parameter, when present, sets the scroll pane's client.

2. It sets the column header for the scroll pane.

3. Set the scroll pane's client.

4. Creates a table with empty cells.

5. It is used to add table of size rows * cols.


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
REFERENCES

[1] Oracle, “Class JTable”, [Online].


Available: https://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html. [Accessed: 5 -Apr-2021].

[2] Geeks for Geeks, “Java Swing - JTable”, [Online].


Available: https:// https://www.geeksforgeeks.org/java-swing-jtable/. [Accessed: 5-Apr-2021].

[3] Javatpoint, “Java JTable”, [Online].


Available: https://www.javatpoint.com/java-jtable. [Accessed: 5-Apr-2021].

[4] Javatpoint, “Java JScrollPane”, [Online].


Available: https://www.javatpoint.com/java-jscrollpane. [Accessed: 5-Apr-2021].
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 1

Course Material No. 15


MENUS FOR MULTIFORM APPLICATIONS

Janus Raymond Tan


Jeruz E. Claudel
Mark Anthony J. Esmeralda
Course Instructor
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 2

15

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Understand the basic rules for Multiform Applications.

• Apply and implement Menu Bar, Menus and Menu Items;

• Apply implement static variables and controls for accessing


(getting) and mutating (setting) data and controls from one
form to another;

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


• For further API reference and developer documentation, see Java SE Documentation.
• Window Builder Plugin -
https://www.eclipse.org/windowbuilder/download.php.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Before you start, try answering the following


questions.
MODULE CONTENTS
1. It used to create a pull-down menu component
which is displayed from the menu bar.

Pre-Activity Title
3
2. It is used to create an object that adds a simple
labeled menu item.
What is Java JMenuBar,
4 JMenu and JMenuItem?

3. It is used to create menu that appears when the


user selects an item on the menu bar. 17 What is
JPopupMenu?

4. It is used create unselected check box menu item 22 What is


with the specified text and icon. JCheckBoxMenuItem?

5. It is used to create a container that groups


26 What is
JToolBar?
several components usually buttons with icons
into a row or column. Post-Test
30 Summary Key
Term
References
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

WORD SEARCH
Find the following words in the puzzle. Words are hidden in different directions.

JMENUITEM
JPOPUPMENU
JMENU
JSEPARATOR
JTOOLBAR

WHAT IS Java JMenuBar, JMenu and JMenuItem?

The JMenuBar class is used to display menubar on the window or


frame. It may have several menus.

The object of JMenu class is a pull-down menu component which is


displayed from the menu bar. It inherits the JMenuItem class.

The object of JMenuItem class adds a simple labeled menu item. The
items used in a menu must belong to the JMenuItem or any of its subclass.

This is the JMenuBar class declaration:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
This is the JMenu class declaration 10

This is the JMenuItem class declaration

JMenuBar, JMenu and a JMenuItem Examples

Java JMenuBar, JMenu and JMenuItem Object Example 1:

The example shows how to make a simple Swing Application with a


JMenuBar, JMenu and a JMenuItem object.

Sample output upon loading FRAME MAIN and clicking the ACCOUNT Menu:

mnAccount
menuBar
mntmLogIn

mntmLogOut

mntmExit
separator
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Specifications of the JMenuBar, JMenu and JMenuItem Object: 10

frameMain Class

JFrame Specifications
Property Value
DefaultCloseOperation EXIT_ON_CLOSE
Title SIMPLE CRUD APPLICATION

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JMenuBar Specifications
Property Value
Variable menuBar

JMenu Specifications
Property Value
Variable mnAccount

JMenuItem Specifications
Property Value
Variable mntmLogIn

JMenuItem Specifications
Property Value
Variable mntmLogOut

JMenuItem Specifications
Property Value
Variable mntmExit

JSeparator Specifications
Property Value
Variable separator
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java JMenuBar, JMenu and JMenuItem Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Note: Notice that in the given example, the JMenuBar object served as a 10
container for the JMenu for Account then the JMenu Account served as the
menu to be clicked so that the drop down of JMenuItem objects for Log In, Log
Out and Exit will appear an be available as choices for the user to select. A
JSeparator object is included to demonstrate its use which is to separate
JMenuItem objects within a JMenu. Additionally, the frameMain is loaded as
a maximized window.

Java JMenuBar, JMenu and JMenuItem Object Example 2:

This example shows how to make a simple Swing Application with a


JMenuBar, JMenu and a JMenuItem object. A separate JFrame for Log In
interface is included and will only appear once the user clicks the JMenuItem
for Log In. Additionally, JMenuItem for Log Out is disabled by default so that
a user can only select among Log In or Exit JMenuItem once the frameMain is
loaded. After successful Log in (by entering “admin” as default username and
password), the JMenuItem for Log In will be disabled, while the JMenuItem
for Log Out will be enabled and vice-versa. The use of public static for
JMenuItem objects is required to make it accessible in other forms specifically,
inside the frameLogIn so that we can change the value for their enabled
properties inside the frameLogin. A confirmation will be asked when the user
selects the JMenuItem for Exit as well as when the user clicks the default
CLOSE Button of the frameMain.

Sample output upon loading FRAME MAIN and clicking the ACCOUNT Menu:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon clicking the LOG IN Menu Item, frameLogIn will appear: GE
10

Sample output upon entering correct username [admin] and password [admin] in
frameLogIn:

Sample output upon clicking the Log In Button in frameLogIn with correct username
[admin] and password [admin] entered:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon successful Log In, the LOG IN Menu Item is disabled, while LOG GE
10
OUT Menu Item is enabled:

Sample output upon clicking the LOG OUT Menu Item, a confirmation message will
appear:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon successful Log Out, a messagedialog will appear: GE
10

Sample output upon successful Log Out, the LOG IN Menu Item is enabled, while
LOG OUT Menu Item is disabled:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon clicking the EXIT Menu Item, a confirmation message will GE
10
appear:

Specifications of the JMenuBar, JMenu and JMenuItem Object:

frameMain Class

JFrame Specifications
Property Value
DefaultCloseOperation EXIT_ON_CLOSE
Title SIMPLE CRUD APPLICATION

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JMenuBar Specifications
Property Value
Variable menuBar

JMenu Specifications
Property Value
Variable mnAccount

JMenuItem Specifications
Property Value
Variable mntmLogIn

JMenuItem Specifications
Property Value
Variable mntmLogOut
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
JMenuItem Specifications GE
Property Value 10
Variable mntmExit

JSeparator Specifications
Property Value
Variable separator

FrameChild Class

JFrame Specifications
Property Value
DefaultCloseOperation DISPOSE_ON_CLOSE
Title LOG IN

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JTextField Specifications
Property Value
Variable txtUserName
Text
X-axis location 111
Bounds Y-axis location 34
Width 157
Height 20

JPassword Specifications
Property Value
Variable txtPassword
Text
X-axis location 111
Bounds Y-axis location 70
Width 157
Height 23

JButton Specifications
Property Value
Variable btnLogIn
Text Log In
X-axis location 26
Bounds Y-axis location 110
Width 89
Height 23

JButton Specifications
Property Value
Variable btnCancel
Text Cancel
X-axis location 179
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
Bounds Y-axis location 110 PA
Width 89 GE
Height 23 10

Java FrameMain Class Program Code:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Java FrameLogIn Class Program Code: GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

WHAT IS JPopupMenu?

The PopupMenu can be dynamically popped up at specific position


within a component. It inherits the JComponent class.

This is the JPopupMenu class declaration:

This is the commonly used Constructors of JPopupMenu:

Figure 1 - Commonly used Constructors Example


from https://www.javatpoint.com/java-jpopupmenu
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
JPopupMenu Examples

Java JPopupMenu Example 1:

This example shows how use and implement a JPopupMenu with


JMenuItems for Cut, Copy and Paste operations that appears when you right
click in the form. A JLabel object displays what particular operation is selected
whenever the user clicks on a JMenuItem inside the JPopupMenu.

Sample output upon loading FRAME MAIN and clicking the FORM using the RIGHT
MOUSE BUTTON:

popupMenu

mntmCut

mntmCopy

mntmPaste
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon clicking the COPY JMenuItem: GE
10

lblOperation

Specifications of the frameMain Class:

JFrame Specifications
Property Value
Title JPopupMenu Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JPopupMenu Specifications
Property Value
Variable popupMenu

JMenuItem Specifications
Property Value
Variable mntmCut

JMenuItem Specifications
Property Value
Variable mntmCopy

JMenuItem Specifications
Property Value
Variable mntmPaste

JLabel Specifications
Property Value
Variable lblOperation
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Java frameMain Class Program Code: GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Note: Notice that in the given example, the JLabel will display text depending on
the selected JMenuItem of the JPopupMenu.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
WHAT IS JCheckBoxMenuItem?

The JCheckBoxMenuItem class represents checkbox which can be


included on a menu. A CheckBoxMenuItem can have text or a graphic icon or
both, associated with it. MenuItem can be selected or deselected. MenuItems
can be configured and controlled by actions [2].

This is the JCheckBoxMenuItem Nested class declaration

This is the commonly used Constructors of the JCheckBoxMenuItem

Figure 2 - Commonly used Constructors Example


from https://www.javatpoint.com/java-jcheckboxmenuitem

This is the Methods used in the JCheckBoxMenuItem

Figure 3 - Commonly used Constructors Example


from https://www.javatpoint.com/java-jcheckboxmenuitem
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
JCheckBoxMenuItem Examples 10

Java JCheckBoxMenuItem Example 1:

This example shows how to use and implement a JCheckBoxMenuItem


as a JMenuItem inside a JMenu which is “unchecked” by default and will
change its text displayed from “Unselected” to “Selected” and vice-versa
whenever the user clicks the JCheckBoxMenuItem. Additionally, a shortcut
key “ALT+F” is assigned to the File JMenu to trigger and show its
JMenuItems.

Sample output upon loading FRAME MAIN and clicking the FILE MENU:

mnFile

menuBar

mntmOpen

chckbxmntmOption
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Specifications of the JCheckBoxMenuItem: GE
10

frameCheckBoxMenuItem Class

JFrame Specifications
Property Value
Title JCheckBoxMenuItem Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JMenuBar Specifications
Property Value
Variable menuBar

JMenu Specifications
Property Value
Variable mnFile

JMenuItem Specifications
Property Value
Variable mntmOpen

JCheckBoxMenuItem Specifications
Property Value
Variable chckbxmntmOption

JLabel Specifications
Property Value
Variable lblOperation
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java frameCheckBoxMenuItem Class Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
WHAT IS JToolBar? 10

The JToolBar container allows us to group other components, usually


buttons with icons in a row or column. JToolBar provides a component which
is useful for displaying commonly used actions or controls.

This is the JToolBar Nested class declaration

This is the commonly used Constructors for the JToolBar

Figure 4 - Commonly used Constructors Example


from https://www.javatpoint.com/java-jtoolbar

JToolBar Examples

Java JToolBar Example 1:

This example shows how use and implement a JToolbar with JButtons
and a JComboBox with items as its sample options for users to select.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon loading FRAME MAIN: GE
10
toolBar

btnHelp

cboItems

btnEdit

btnFile

Specifications of the JToolBar:

frameToolBar Class

JFrame Specifications
Property Value
Title JToolBar Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JToolBar Specifications
Property Value
Floatable false
Variable toolBar

JButton Specifications
Property Value
Text FILE
Variable btnFile

JButton Specifications
Property Value
Text EDIT
Variable btnEdit

JComboBox Specifications
Property Value
Variable cboItems
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

JButton Specifications
Property Value
Text HELP
Variable btnHelp

Java frameToolBar Class Program Code:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

CREATING YOUR JAVA JMENUBAR, JMENU, AND JMENUITEM

Task:

1. Create a Java JMenuBar, JMenu, and JMenuItem displaying the Menu Bar.
2. In create a menu, you have to construct a menu bar and attach it to the frame. Then add a menu
named file to the menu bar.
3. Lastly, create a menu item named new and add to the file menu.

Example Output:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
SUMMARY 10

A pull-down menu component that is presented from the menu bar is the
JMenu class's object.
The MenuBar on the window or frame is displayed using the JMenuBar class.
There could be multiple menus.
A CheckBoxMenuItem may be accompanied by text, a visual icon, or both.
You can pick or deselect a menu item.
Anywhere else a menu should appear and you can use a JPopupMenu.

You can arrange additional elements, most frequently buttons with icons in a
row or column, using the JToolBar container. A handy component for
displaying frequently used actions or controls is offered by JToolBar.

KEY TERMS

JMenu

JMenuItem

JToolBar

JPopupMenu

JCheckBoxMenuItem

JSeparator

POST-TEST

Directions: Identify the given statements below.

1. Creates a container that allows to group other components, usually buttons with icons in a row or column.

2. Creates a new Menu with no text.

3. This class represents a check box which can be included in a menu.

4. Creates a small window that pops up and displays a series of choices.

5. It is used to create a menu to separate groups of related menu items.


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
REFERENCES 10

[1] Javatpoint, “Java JPopupMenu”, [Online].


Available: https: https:// https://www.javatpoint.com/java-jpopupmenu. [Accessed: 5-May-2021].

[2] Javatpoint, “Java JCheckBoxMenuItem”, [Online].


Available: https: https:// https:// https://www.javatpoint.com/java-jcheckboxmenuitem. [Accessed: 5-May-2021].

[3] Javatpoint, “Java JToolBar”, [Online].


Available: https: https:// https:// https://www.javatpoint.com/java-jtoolbar. [Accessed: 5-May-2021].

[4] WhatIs, “Menu”, [Online].


Available: https: https://whatis.techtarget.com/definition/menu. [Accessed: 30-Apr-2021].

[5] Microsoft Build, “Menus (Design Basics)”, [Online].


Available: https: https://docs.microsoft.com/en-us/windows/win32/uxguide/cmd-menus. [Accessed: 30-
Apr-2021]
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE
PA
GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 1

Course Material No. 16-17


MORE ADVANCED GUI CONTROLS

Janus Raymond Tan


Jeruz E. Claudel
Mark Anthony J. Esmeralda
Course Instructor
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2 2

16

LEARNING OUTCOMES

Here’s what I will teach you in this course material:

• Understand how to build form applications and implement


GUI controls and events appropriate to the requirements of
the programming problem.

• Apply how to use of JProgressBar, JSpinner, JSlider and


JTree Class objects in a Java Swing Application

• Apply and understand the use of JTabbedPane, JDialog and


JToggleButton Class objects in a Java Swing Application

RESOURCES NEEDED

For this lesson, you would need the following resource/s:

• Eclipse IDE - http://www.eclipse.org/downloads/


• For further API reference and developer documentation, see Java SE Documentation.
• Window Builder Plugin -
https://www.eclipse.org/windowbuilder/download.php.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

Before you start, try answering the following


questions.
MODULE CONTENTS
1. It is part of Java Swing package that is used to
create visual displays on the progress of some
specified task.

Pre-Activity Title
3
2. It is used to create an empty spinner with an
What is Java
initial value set to zero and has no
constraints.
4 JProgressBar?

3. It is used to create the user graphics that selects a


11 What is JSpinner?

value by sliding a knob within a bounded


interval.
13 What is JSlider?

4. It is used create a display of the tree structured data


What is JTree,
or hierarchical data.
14 JTabbedPane, JDialog,
and JToggleButton?

5. It is used to create user a switch between a Post-Test


group of components by clicking on a tab with 35 Summary Key
Term
a given icon.
References
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

SCRAMBLE WORD SEARCH


Scramble the letters and provide the correct answer on the blank spaces below.

SPRSOGRAJBER
RSEJNNIP
IDERLJS
JRETE
NELPAJ

WHAT IS Java JProgressBar?

The JProgressBar class is used to create a visual display of the progress


of the task in which this component can be horizontal or vertical.

This part of java swing package displays the percentage of completion


of a specified task.

This is the JProgressBar class declaration:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
This is the JProgressBar class commonly used constructors: 10

Figure 1 - Commonly used Constructors Example


from https://www.javatpoint.com/java-jprogressbar

This is the JProgressBar class commonly used methods:

Figure 2 - Commonly used Methods Example


from https://www.javatpoint.com/java-jprogressbar

JProgressBar Examples

Java JProgressBar Example 1:

The example This example shows to implement a JProgressBar class in


creating a simple splash screen of your Java Swing Application. Two frames
are needed in order to make a splash screen. The frameMain class will execute
the application by first creating and showing the frameSplashScreen object on
user’s screen. After loading the JProgressBar from 0 to 100 percent, the
frameMain object will be shown on user’s screen while disposing the
frameSplashScreen object. Additionally, a GIF loading image is set as an icon
image of a JLabel set on top of the entire frameSplashScreen object.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon running the program, loading the Splash Screen from 0 to GE
10
100%:

frameSplashScreen Class

lblImage

lblLoadingText

progressBar

Sample output after loading the Splash Screen from 0 to 100%:

frameSplashScreen Class
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
Sample Project Folder:

Note: An image folder as a SOURCE FOLDER is created as storage of the


GIF Loading Image.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Specifications of the frameMain Class: 10

JFrame Specifications
Property Value
Title SAMPLE APPLICATION

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

Specifications of the frameSplashScreen Class:

JFrame Specifications
Property Value
Undecorated true

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JLabel Specifications
Property Value
Variable lblLoadingText
Text Loading…

JProgressBar Specifications
Property Value
Variable progressBar
Maximum 100
Minimum 0
Orientation Horizontal
StringPainted true
Value 0

JLabel Specifications
Property Value
Variable lblImage
Text
VerticalAlign Center
x 0
Bounds y 0
width 800
height 600
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java frameMain Class Program Code: 10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
Java frameSplashScreen Class Program Code: 10

Note: An image folder as a SOURCE FOLDER is created as storage of the


GIF Loading Image.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

WHAT IS JSpinner?
?
A single line input field serves as the object of the JSpinner class and
enables the user to choose a number or object value from an ordered list. This
object can be type manually in a legal data going into text field of the class.
The JSpinner is ideal object because it does not need a drop-down list
and has an element of an upward and a downward arrow.

This is the JSpinner class declaration:

This is the commonly used Constructors of JSpinner:

Figure 3 - Commonly used Constructors Example


from https://www.javatpoint.com/java-jspinner

This is the JProgressBar class commonly used methods:

Figure 4 - Commonly used Methods Example


from https://www.javatpoint.com/java-jspinner
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
JSpinner Examples

Java JSpinner Example 1:

This example shows how use and implement a JSpinner object by


setting the initial value, minimum value, maximum value and the step value. A
Change Listener is used to update the text displayed in a JLabel based on the
value displayed in the JSpinner.

Sample output upon loading FRAME MAIN and clicking the INCREASE
button of the JSpinner:

spinner

lblDisplay

Specifications of the frameMain Class:

JFrame Specifications
Property Value
Title JSpinner Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JSpinner Specifications
Property Value
Variable spinner
Number type:
Initial Value: 0
Model Minimum: 0
Maximum: 100
Step Size: 1
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
JLabel Specifications 10
Property Value
Variable lblDisplay

Java frameMain Class Program Code:

Note: Notice that in the given example, the JLabel will display text whenever
the user updates the value displayed in the JSpinner by clicking its up and
down arrow buttons.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
WHAT IS Java JSlider?
?
The JSlider Class is used to create a slider and by using this the user
can choose a value from a predetermined range by using this class and only
those locations are permitted for the knob.

This is the commonly used Constructors of the JSlider

Figure 5 - Commonly used Constructors for Slider Example


from https://www.javatpoint.com/java-jslider

This is the Methods used in the JSlider

Figure 6 - Commonly used Methods for Slider Example


from https://www.javatpoint.com/java-jslider
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
JSlider Examples

Java JSlider Example 1:

This example shows how use and implement a JSlider object by setting
the default orientation, minimum value, maximum value and the initial value.
A Change Listener is used to update the text displayed in a JLabel based on
the value set in the JSlider.

Sample output upon loading FRAME MAIN:

slider

lblDisplay

Specifications of the frameJSlider Class:

JFrame Specifications
Property Value
Title JSlider Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JSlider Specifications
Property Value
Variable Slider
MajorTickSpacing 10
Maximum 50
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
Minimum 0 PA
MinorTickSpacing 2 GE
Orientation Horizontal 10
PaintLabels true
PaintTicks true
PaintTrack true
Value 25

JLabel Specifications
Property Value
Variable lblDisplay

Java frameMain Class Program Code:

Note: Notice that in the given example, the JLabel will display text whenever
the user updates the value displayed in the JSlider by sliding the slider button.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
WHAT IS JTree?

The hierarchical data is shown in a tree-like manner using a JTree and


the node is the name for each element of the class in other words this is used to
display structured data. It actually enables three alternative modes for node
selection by the user.

This is the JTree class declaration

This is the commonly used Constructors for the JTree

Figure 7 - Commonly used Constructors for JTree Example


from https://www.javatpoint.com/java-jtree

JTree Examples

Java JTree Example 1:

This example shows how use and implement the JTree class in a simple
Java Swing Application.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon loading FRAME MAIN: GE
10

tree

Sample output upon clicking the color tree node:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Specifications of the frameJTree Class: GE
10

JFrame Specifications
Property Value
Title JTree Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JTree Specifications
Property Value
Variable tree
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Java frameJTree Class Program Code: GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
WHAT IS JTabbedPane?

The JTabbePane lets you create a user switch between a certain page by
simply clicking the tab and also for users to input data into the application.
Multiple components, such as panels, can share the same space when using the
JTabbedPane class.

This is the JTabbedPane class declaration

This is the JTabbedPane Commonly used Constructors

Figure 8- Commonly used Constructors for JTabbedPane Example


from https://www.javatpoint.com/java-jtabbedpane

JTabbedPane Examples

Java JTabbedPane Example 1:

This example shows to implement a JTabbedPane class in a Java Swing


Application. A JPanel will be used as container to represent every tab of the
JTabbedPane object whichn means in this example, we have three JPanel
objects with tab with tab tiles such as College Management, Course
Management and Student Management. Every JPanel, a JLabel object is
included. By default, the tab placement is on top of the JTabbedPane object.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon running the program, College Management is the selected tab: GE
10

tabbedPane

panelCollege

lblCollege

Sample output upon clicking the Course Management tab:

tabbedPane

panelCourse

lblCourse
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon clicking the Student Management tab: GE
10

tabbedPane

panelStudent

lblStudent

Specifications of the frameMain Class:

JFrame Specifications
Property Value
Title JTabbedPane Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JTabbedPane Specifications
Property Value
Variable tabbedPane
Tab Layout Policy WRAP_TAB_LAYOUT
Tab Placement Top

JPanel Specifications
Property Value
Variable panelCollege
Layout absolute
Tab Title College Management
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
JPanel Specifications 10
Property Value
Variable panelCourse
Layout absolute
Tab Title Course Management

JPanel Specifications
Property Value
Variable panelStudent
Layout absolute
Tab Title Student Management

JLabel Specifications
Property Value
Variable lblCollege
Text COLLEGE

JLabel Specifications
Property Value
Variable lblCourse
Text COURSE

JLabel Specifications
Property Value
Variable lblStudent
Text STUDENT
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Java frameMain Class Program Code: GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
WHAT IS JDialog?

When using JDialog(), a modeless dialog without a title or a defined


Frame owner is created. The primary goal of this class is to expand it with new
elements and can be altered to suit user requirements. This is in contrast to
JFrame in which it does not have the maximize and minimize buttons.

This is the JDialog class declaration

This is the JDialog Commonly used Constructors

Figure 9- Commonly used Constructors for JDialog Example


from https://www.javatpoint.com/java-jdialog

JDialog Examples

Java JDialog Example 1:

This example shows how use and implement a Custom JDialog Class
by inheriting the JDialog Class. A frameMain Class object (inherits the JFrame
Class) is used as the main window with a JButton object that will open the
object of the Custom Dialog Class to be created. The Custom JDialog object
will be set as a MODAL of the frameMain Class object so that the user will not
be allowed to interact with the main window except when the user already
closes the Custom JDialog object.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon loading FRAME MAIN: GE
10
btnOpen

frameMain

Sample output upon clicking the Open Dialog Button of the FRAME MAIN:

dialogSample

contentPanel

lblDialog

btnOk

btnCancel

buttonPane

Specifications of the frameMain Class inherits the JFrame Class:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
JFrame Specifications 10
Property Value
Title JDialog Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JButton Specifications
Property Value
Variable btnOpen
x 25
Bounds y 22
width 113
height 29
Text Open Dialog

Specifications of the dialogSample Class inherits the JDialog Class:

JDialog Specifications
Property Value
DefaultCloseOperation HIDE_ON_CLOSE
Modal true
Resizable false
Title SAMPLE DIALOG BOX

JPanel Specifications
Property Value
Variable contentPanel
Layout absolute
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
JPanel Specifications PA
Property Value GE
Variable buttonPane 10
Layout FlowLayout

JLabel Specifications (added in contentPanel)


Property Value
Variable lblDialog
Layout I’AM A DIALOG BOX

JButton Specifications (added in buttonPane)


Property Value
Variable btnOk
Text Ok

JButton Specifications (added in buttonPane)


Property Value
Variable btnCancel
Text Cancel

Java frameMain Class inherits the JFrame Class Program Code:


PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Java dialogSample class inherits the JDialog Class Program Code: GE
10

Note: Notice that in the given example, clicking outside the Custom Dialog
object will not be possible since we set the dialogSample Class as a MODAL
of the frameMain Class object upon user’s click on the Open Dialog Button.
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10
WHAT IS JToggleButton?

To describe buttons that can be toggled ON and OFF, you can use a
JToggleButton, which is an extension of AbstractButton. The toggle button
toggles between being pressed and being unpressed when the user presses it.

This is the JToggleButton Nested Classes

Figure 10- Nested Classes for JToggleButton Example


from https://www.javatpoint.com/java-jtogglebutton

This is the JToggleButton Commonly used Constructors

Figure 11- Commonly used Constructors for JToggleButton Example


from https://www.javatpoint.com/java-jtogglebutton
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
This is the JToggleButton Commonly used Methods 10

Figure 12- Commonly used Methods for JToggleButton Example


from https://www.javatpoint.com/java-jtogglebutton

JToggleButton Examples

Java JToggleButton Example 1:

This example shows how use and implement a JToggleButton object


that will change the text displayed to “ON” when selected, “OFF” if not
selected. “OFF” is the text displayed by default which means by running the
program, the JToggleButton object is not selected. An Item Listener is used to
determine the current state of the JToggleButton.

Sample output upon loading FRAME MAIN, the JToggleButton is not selected, that
is why “OFF” is the text displayed:

tglbtnOnOff
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Sample output upon clicking the JToggleButton, the JToggleButton becomes selected, GE
10
that is why “ON” is the text displayed:

Specifications of the frameToggleButton Class:

JFrame Specifications
Property Value
Title JToggleButton Example

JPanel Specifications
Property Value
Variable contentPane
Layout absolute

JToggleButton Specifications
Property Value
Variable tglbtnOnOff
x 162
Bounds y 114
width 104
height 140
Selected False
Text OFF
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
Java JToggleBar Class Program Code: GE
10
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
10

CREATING JAVA CLASS JTABBEDPANE

Task:

1. Create a Java JTabbedPane, add the Tab pane in JFrame then add components on each tab
2. Create a Java Class named AddJTabbedPane.java in which I describe the user interface.
3. In the created JFrame add two tabs named 'Fruit' and 'Vegetable' onto the JFrame.
4. Lastly, make sure that whenever you switch to Vegetable tab then the vegetable's name will be
displayed.

Example Output:
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
SUMMARY 10

A horizontal progress bar with the supplied minimum and maximum value is
created using JProgressBar.
A component of the class JSpinner allows the user to choose a number or
object value from an ordered sequence via an input field.
JSlider is used to allow the user to visually select a value by turning a knob
within a defined range.
To show tree-structured or hierarchical data, you can use the JTree class.
By simply clicking on one of the tabs, JTabbedPane gives the user the freedom
to navigate between various groupings of components he wants to see.
In order to create a window-based application, this serves as a top-level
container on which various lightweight JAVA swing components can be
added.
Toggle buttons, which may be turned on or off, are made using the
JToggleButton class.

KEY TERMS

JProgressBar

JSpinner

JSlider

JTree

JTabbedPane

JDialog

JToggleButton
PAMANTASAN NG CABUYAO |COMPUTER PROGRAMMING 2
PA
GE
POST-TEST 10

Directions: Identify the given statements below.

1. This is another component of java class which is much similar to a JButton.

2. This creates a type of graphic interface used to show how a prolonged computer activity
is progressing.

3. This class represents a tree-structured or hierarchical data.

4. This java class allows the user to visually select a value by turning a knob within a defined range.

5. It is used to t enables the user to transition between a series of features by selecting a tab
with a certain title and/or icon.

REFERENCES

[1] Javatpoint, “Java JTabbedPane”, [Online].


Available: https://www.javatpoint.com/java-jtabbedpane. [Accessed: 1-Jun-2021].

[2] Javatpoint, “Java JDialog”, [Online].


Available: https://www.javatpoint.com/java-jdialog. [Accessed: 1-Jun-2021].

[3] Javatpoint, “Java JToggleButton”, [Online].


Available: https://www.javatpoint.com/java-jtogglebutton. [Accessed: 1-Jun-2021].

[4] Javatpoint, “Java JProgressBar”, [Online].


Available: https://www.javatpoint.com/java-jprogressbar. [Accessed: 28-May-2021].

[5] Javatpoint, “Java JSpinner”, [Online].


Available: https://www.javatpoint.com/java-jspinner. [Accessed: 28-May-2021].

[6] Javatpoint, “Java JCheckBoxMenuItem”, [Online].


Available: https://www.javatpoint.com/java-jcheckboxmenuitem. [Accessed: 28-May-2021].

[7] Javatpoint, “Java JTree”, [Online].


Available: https://www.javatpoint.com/java-jtree. [Accessed: 28-May-2021]
PAMANTASAN NG CABUYAO |YOUR COURSE TITLE HERE
PA
GE
10

You might also like