Uploaded by Jason Reyes

ICS2606-Finals

advertisement
Intro to IO and File IO
Course
Date
ICS2606 | Computer Programming II
@March 22, 2023
Module
Module 7
Mode
Synchronous
If-Task
Lecture
Progress
Not Started
Mastery
None
Sub-item
Resources
Last Study
Parent item
Due
-62 day(s)
Days Left
-63
Parent item 1
Section
Sub-item 1
Task Content
https://drive.google.com/file/d/1uEJ80ZZi7R8x59sebIDRgZbeGAbnyg2u/view?usp
=sharing
Outline:
IO Fundamentals
Intro to IO and File IO
1
Fundamental Stream Classes
Data within Streams
IO Stream Chaining
How to Accept Inputs Using
The
BufferedReader
The
Scanner
GUI - the
and
InputStreamReader
Classes
Class
JOptionPane
Component
How to format an output
System.out.printf()
String.format()
The
File
method
method
class
How to read inputs from a
How to write output to a
File
File
How to read and write to a binary
File
IO Stream Fundamentals
Stream - is defined as a flow of data from a source to a destination or a sink.
Source - stream initiates the flow of data while the
Sink (destination) - terminates the flow of data
Sources are also called Input Streams and the sinks are also called the Output
Streams.
Sources and sinks are both Node Streams also called as End-Points.
These streams can be opened and closed before and after the input and
output of data is finished
There are different types of nodes or end points, there are file nodes, memory
nodes, and pipes or thread nodes
Thread nodes will be discussed more in ICS2608
Node vs Stream
Intro to IO and File IO
2
Node - is the connection of the end-points, from source to sink
Stream - is the flow of information or data in the nodes
Fundamental Stream Classes
Java maintain two group of streams, the Byte streams and the Character
Streams, both of which have their respective input and output streams classes
Stream
Byte Stream
Character Stream
Source Streams
InputStream
Reader
Sink Streams
OutputStream
Writer
Input/Output - is for Byte, think of a robot using byte code
Reader/Writer - for Character since paragraphs require human skill, think of it as
computer input/output and human reads/writes
Data within Streams
There are classes under the java.io package that allows the conversion of nonUnicode text or byte streams to Unicode text of character streams and vice versa.
Readers
and
Writers
classes handle the Unicode text, while byte streams
handle the non-Unicode text
For each type of node, there corresponds a specific class that will handle the byte
stream and the character streams
Most methods from the byte stream classes are also present in the character
streams classes that is why in most cases, what ever functionality that a byte
stream can do can also be done by the character streams, the only difference
between these two streams are the type of character they process
byte streams processes non Unicode data
character streams processes Unicode data
Sample Node Streams
Type
Byte Streams
Character Streams
File
FileInputStream
Memory Array
ByteArrayInputStream
Intro to IO and File IO
FileOutputStream
ByteArrayOutputStream
FileReader
FileWriter
CharArrayReader
CharArrayWritter
3
Type
Byte Streams
Memory String
N/A
Pipe
PipeInputStream
Character Streams
StringReader
PipeOutputStream
PipedReader
StringWriter
PipedWriter
IO Stream Chaining
To allow creating of complex I/O processing java uses the concept of ‘chaining’
streams.
this means that an instance of one Stream is passed as a parameter to the
constructor of another
How to Accept Inputs using — the
BufferedReader
and
InputStreamReader
Classes
import java.io.*;
public class KeyboardInput {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter values and press ^D to end");
String str;
//we want every instance we put it in the condition instead of the string variable
while ((str = br.readLine()) != null) { // will check the new input
System.out.println(str + ", was typed.");
// str = br.readLine(); can also be placed here
}
br.close();
}
Intro to IO and File IO
4
}
//^Z is null in Command.com
//^D is null in terminal = Unix window
BufferedReader
- requires input to be of Character-input Stream
reach read request made of a Reader causes a corresponding read request
to be made
BufferedReader(Reader in)
- constructor creates a buffering character-input
stream that uses a default-size input buffer
The Conversion of
String
to other data type
since the readLine() method accepts
different types into String
Conversion of
String
Strings
we would want to convert the
to integral values
String strNum "100";
byte bNum = Byte.parseByte(strNum);
short sNum = Short.parseShort(strNum);
int iNum = Integer.parseInt(strNum);
long lNum = Long.parseLong(strNum);
Conversion of
String
to
float
or
double
values
String sNum = "1.1";
float fNum = Float.parseFloat(sNum);
double dNum = Double.parseDouble(sNum);
Conversion of
String
to
boolean
value
String str = "true";
boolean bool = Boolean.parseBoolean(str);
When accepting values using the readLine() method of the
the returned values are of type String
How to Accept Inputs using — The
Intro to IO and File IO
Scanner
BufferedReader
class
Class
5
The
Scanner
class is found in the
java.util
package.
It is used to accept formatted inputs from any data source using the
object
Data Types
The
Scanner nextXxx()
byte
nextByte()
short
nextShort()
int
nextInt()
long
nextLong()
float
nextFloat()
double
nextDouble()
boolean
nextBoolean()
char
next().charAt(0)
String
next() or nextLine()
Scanner
methods
— there is no
nextChar()
Scanner s = new Scanner(System.in);
System.out.println("Enter a String value: ");
String str = s.nextLine();
System.out.println("The String value is: " + str);
int num;
System.out.println("Enter an int value: ");
num = s.nextInt();
System.out.println("The next value is: " + ++num);
System.out.println("Enter a byte value: ");
byte b = s.nextByte();
System.out.println("Enter a short value: ");
short sh = s.nextShort();
System.out.println("Enter a long value: ");
long lo = s.nextLong();
System.out.println("Enter a float value: ");
float fl = s.nextFloat();
System.out.println("Enter a double value: ");
double d = s.nextDouble();
System.out.println("Enter a boolean value: ");
boolean bool = s.nextBoolean();
Intro to IO and File IO
6
System.out.println("Enter a character value: ");
char ch = s.next().charAt(0);
System.out.println("The
System.out.println("The
System.out.println("The
System.out.println("The
System.out.println("The
System.out.println("The
System.out.println("The
System.out.println("The
byte value is: " + b);
short value is: " + sh);
int value is: " + num);
long value is: " + lo);
float value is: " + fl);
double value is: " + d);
boolean value is: " + bool);
char value is: " + ch);
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = s.nextLine(); //String w/a space
//String name = s.next(); //single string only
System.out.print("How old are you? ");
double age = s.nextInt();
System.out.print("What is your GPA? ");
double gpa = s.nextDouble();
System.out.println("Hello " + name + ", next year you'll be " +
(age + 1) + " years old.");
s.close();
}
}
How to Accept Inputs using — the
JOptionPane
Class
Another way to get inputs from the user is by using the
the javax.swing package
JOptionPane
class found in
makes it easy to display a dialog box that prompts users for a value
or to display a message
JoptionPane
Intro to IO and File IO
7
import javax.swing.JOPtionPane;
public class KeyboardReaderGUI {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog("What is your name?");
String msg = "Hello " + name + "! How are you doing?");
JOptionPane.showMessageDialog(null, msg);
}
}
How to format your output —
String.format()
and
System.out.printf()
During Java 1.4 days, it will take several lines of codes to format an output the
way you wanted them to appear, but since the birth of 5.0, formatting an output
has never been easy
With the use of
String.format()
or the
System.out.printf()
, methods you can use
these methods to format a output
Code
Description
Formats the argument as a String, usually by calling the
%s
toString()
method
on the object
%d
%o
%f
%g
%x
Formats an integer as a decimal, octal or hexadecimal value
Formats a floating point value,
%g
uses scientific notation
%n
Inserts the newline character to the String or stream
%%
Inserts the
%
character to the String or stream
The File Class
public class File extends Object implement Serialization, Comparable<File>
an abstract representation of file and directory pathnames
Intro to IO and File IO
8
- File myFile;
- myFile = new File("myfile.txt");
- myFile = new File("MyDocs", "myfile.text");
Directories are treated just like files in the Java programming language. You can
create a File object that represents a directory and then use it to identify other
files, for example:
File myDir = new File("MyDocs");
myFile = new File(myDir, "myfile.txt");
The relationship between the
File
Object and the Physical File on your Hard
Drive Class
Let’s say you have this:
File myFile = new File("myfile.txt");
Once a
File
object has been instantiated, a link of that
File
object on the
physical file you have on your hard drive will be established
The
Intro to IO and File IO
File
object serves as a mirror to your physical file
9
A
object will then be created in the heap memory linking itself to your file
myfile.txt on your hard drive
File
You can then gain access to that file object by its reference variable
myFile
.
Common File Tests and Utilities Methods
Under the
java.io.File
class, there are helper methods that can retrieve
information, tests the file or even check whether the files were modifies.
File Information
String getName()
String getPath()
String getAbsolutePath()
String getParent()
long lastModified()
long length()
File Modification
boolean renameTo(File newName)
boolean delete()
Directory utilities
boolean mkdir()
String[] list()
File tests
boolean
boolean
boolean
boolean
boolean
boolean
boolean
exists()
canWrite()
canRead()
isFile()
isDirectory()
isAbsolute()
isHidden()
Reading Inputs from a
Intro to IO and File IO
File
10
Reading and Writing data to a file is possible in application programs but are not
possible in Applets
The class that is responsible for reading data from a file is the
FileReader
class:
BufferedReader br = new BufferedReader (new FileReader(MyFile));
The
br
is a reference name variable, while the
myFile
is the name of the file
where data will be read
ReadFile.Java
import java.io.*;
public class ReadFile {
public static void main(String[] args) throws IOException {
int ctr = 0;
File myFile = new File(args[0]);
//FileReader fr = new FileReader(myFile);
//BufferedReader br = new BufferedReader(fr);
BufferedReader br = new BufferedReader(new FileReader(myFile));
String str = br.readLine();
while(str != null) {
System.out.println(++ctr + ": " + str);
}
br.close();
}
}
Writing Output to a
File
to enable the write capability to a file, we use
out
FileWriter
class
is a reference variable that will display the stream to the specified file
myFile
is the name of the file where inputted String will be stored
import java.io.*;
public class WriteFile {
public static void main(String[] args) throws IOException {
File myFile = new File(args[0]);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter output = new PrintWriter(new FileWriter(myFile, true));
System.out.println("Enter text and press ^Z or ^D to end");
String str = br.readLine();
Intro to IO and File IO
11
while(str != null) {
//System.out.println(str);
output.println(str);
str = br.readLine();
}
br.close();
output.close();
}
}
Read / Write to a Binary
File
All byte stream classes descends from the
InputStream
and
OutputStream
classes
These byte stream classes are used for reading and writing 8-bit data
import java.io.*;
public class TestCopyBytes {
public static void main(String[] args) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(args[0]);
out = new FileOutputStream(args[1]);
int c;
//returns -1 if there's no more
//bytes to read from the stream;
while( (c - in.read()) != -1 ) {
out.write(c);
}
} finally {
//Always close the stream
if(in != null) { in.close(); }
if(out != null) { out.close(); }
}
}
}
Intro to IO and File IO
12
Collections and the Generic
Framework
Course
Date
ICS2606 | Computer Programming II
@March 29, 2023
Module
Module 8
Mode
Synchronous
If-Task
Lecture
Progress
Not Started
Mastery
None
Sub-item
Resources
Last Study
Parent item
Due
-55 day(s)
Days Left
-56
Parent item 1
Section
Sub-item 1
Task Content
https://drive.google.com/file/d/1orBcEWge4luSyyC27Y7iabfwLUeXKlKA/view?us
p=sharing
Collections and the Generic Framework
1
Introduction:
The Collection Interface
The Set Interface
The List Interface
The Map Interface
The Iterator Interface
The Generics Framework
Creating a Collection of User-Defined Objects
Sorting your set
Sorting your list
Sorting your map
Filtering your map
by key
by value
The
Collection
Interface
The root interface in the collection hierarchy
a collection represents a group of object, known as its elements
some collections allow duplicate elements and others do not
some are ordered and others are unordered. The JDK does not provide any
direct implementation of this interface: it provides implementations of more
specific sub-interfaces like Set and List
This interface is typically used to pass collections around and manipulate them
where maximum generality is desired
Collections and the Generic Framework
2
Collections vs Arrays
The
Collections
Arrays
Is a single object that represents a group of
objects known as its elements
Is a single objects that represent a group
of objects or primitive values
Is thread-safe, heavy weight
Is NOT thread-safe, light weight
Set
Interface
An unordered collection, sequence is not ensured
Duplicated are NOT permitted. All elements are unique
At most, only one element can be set to null
Collections and the Generic Framework
3
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set set = new HashSet();
set.add("Lawrence");
set.add(new Integer(100));
set.add(new Boolean(false));
set.add("java");
set.add("java");
set.add("Lawrence");
set.add(new Double(3.0));
System.out.println(set);
}
}
//Output
[java, 100, false, Lawrence, 3.0]
The
List
Interface
An ordered collection (also known as a sequence)
The user of this interface has precise control over where in this list each
element is inserted
The user can access elements by their integer index (position in the list), and
search for elements in the list
Duplicates are permitted
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List list = new ArrayList();
list.add("Lawrence");
list.add(new Integer(100));
list.add(new Boolean(false));
list.add("java");
list.add("java");
list.add("Lawrence");
list.add(new Double(3.0));
System.out.println(list);
Collections and the Generic Framework
4
}
}
[Lawrence, 100, false, java, java, Lawrence, 3.0]
The
Map
Interface
A Map is a data structure used to hold elements that can be accessed through a
unique identifier.
It is made up of a
K-V
(key, value) pair
A map cannot contain duplicate keys; each key can map to at most one value
You map / connect / relate / pair a unique key to a specific value
Both the key and the value are objects
To navigate to a map, you need to get this key using the
KeySet()
method
import java.util.*;
public class MapExample {
public static void main(String[] args) {
Map map = new HashMap();
map.put("one", "uno");
map.put("two", "dos");
map.put("three", "dos");
//Overwrites the previous assignment
map.put("three", "tres");
//Returns set view of keys
Set set1 = map.keySet();
System.out.println(set1);
//Returns Collection of view of values
Collection collection = map.values();
System.out.println(collection);
//Returns set of view of key value mappings
Set set2 = map.entrySet();
System.out.println(set2);
System.out.println(set1 + "\n" + collection + "\n" + set2);
}
}
Collections and the Generic Framework
5
[one, two, three]
[uno, dos, tres]
[one=uno, two=dos, three=tres]
[one, two, three]
[uno, dos, tres]
[one=uno, two=dos, three=tres]
The
Iterator
and
ListIterator
Interface
An iterator is an object that can be used to loop through collections, like
ArrayList
and
HashSet
It is called an “iterator” because “iterating” is the technical term for looping.
Iterators can only support forward iteration
Like the
Iterator
interface,
ListIterator
iterate elements one-by-one from a
List
is a Java iterator, which is sued to
implemented object like
ArrayList
unlike Iterator, it supports both forward and backward iterations
Collections and the Generic Framework
6
The Generics Framework
The Generics Framework was introduced in Java SE 5.0 and provides support
that allows for the parameterization of types called <E>
It reduces the amount of code that needs to be written when placing (or
retrieving) an object to (or from a) collection
Generics provides a compile-time type safely that allows programmers to catch
invalid types at compile time
Using generics, it eliminates the use for a cast
It is denoted by the diamond operator with a type in it (<E>)
//Before Generics
List myList = new ArrayList();
myList.add(0, new Integer(100));
int num = ((Integer) myList.get(0)).intValue();
Collections and the Generic Framework
7
//After Generics
List<Integer> myList = new ArrayList<Integer>();
myList.add(0, new Integer(100));
int num = myList.get(0).intValue();
Generics can be applied to all
Collection
and
Map
Interfaces
It allows us to create homogenous collections
List<String> names = new ArrayList<String>();
names.add("Lawrence");
names.add("Percy");
names.add(100); //compilations error
The Diamond ( <> ) Operator
Before Java SE 7, we have to specify the type of object that we will put in our
collection
This should be done on both the declaration and in the instantiation part
List<String> names = new ArrayList<String>();
names.add("Lawrence"):
names.add("Percy");
Map <Integer, String> employees = new HashMap<Integer, String>();
employees.put(1, "Ericson");
employees.put(2, "Jerry");
Starting Java 7, you don’t have to specify the type in the instantiation part.
List<String> names = new ArrayList<>();
names.add("Lawrence"):
names.add("Percy");
Map <Integer, String> employees = new HashMap<>();
employees.put(1, "Ericson");
employees.put(2, "Jerry");
Collection of the User-Defined Objects
Collections and the Generic Framework
8
The
Class
Person
Person
name: String age: int
Person(String name, int age) getName( ) : String getAge( ) : int
equals ( ) : boolean hashCode ( ) : int toString ( ) : String
1. We will create a class
Person
2. In a test class, we will create a
HashSet
3. We will iterate through our
of
Sorting your
Set
that will contain
Person
Person
objects
objects and display them
— Using the Comparable Interface
Set
<<Interface>> Comparable
Person
name: String age: int
Person(String name, int age) getName ( ) : String getAge ( ) : int
equals ( ) : boolean hashCode ( ) : int toString ( ) : String compareTo
(T o) : int
1. Implement the
2. Override the
3. Use
TreeSet
4. Create an
Sorting your
Comparable
interface in the Person class
compareTo(T o)
instead of
Iterator
List
method from the
Comparable
interface
HashSet
object to iterate through our
Set
— Using the Comparable Interface
<<Interface Comparable>> Comparable
Person
name: String age: int
Person(String name, int age) getName ( ) : String getAge ( ) : int
equals ( ) : boolean hashCode ( ) : int toString ( ) : String compareTo
(T o) : int
Collections and the Generic Framework
9
1. Implement the
2. Override the
3. Call the
Comparable
interface in the Person class
compareTo(T o)
method from the
Comparable
interface
to sort in ascending order or
Collections.reverseOrder()) to sort in descending order
Collections.sort(list)
Collections.sort(list,
4. Create an
Sorting Your
Iterator
object to iterate through our
— Using the
Map
Map.Entry
List
to retrieve objects from a
TreeMap
<<Interface Comparable>> Comparable
Person
name: String age: int
Person(String name, int age) getName ( ) : String getAge ( ) : int
equals ( ) : boolean hashCode ( ) : int toString ( ) : String compareTo
(T o) : int
1. Implement the
2. Override the
3. Use the
Comparable
interface in the Person class
compareTo(T o)
TreeMap
to sort the
method from the
Map
Comparable
by keys automatically
4. Use the enhanced for loop to iterator through our
Use
Map.Entry
Filtering a
Map.Entry
Map
by a
TreeMap
object
interface that provide methods to access the entry in the
By gaining access to the entry of the
The
interface
Map
Map
objects are easier to retrieve
is a generic interface and it defined in the
Java.util
package
Key
Map<Integer, String> employees = new HasMap<>():
employees.put(35,
employees.put(29,
employees.put(43,
employees.put(31,
employees.put(25,
"Peter");
"Mark");
"Luke");
"John");
"James");
//filtering by key
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
Collections and the Generic Framework
10
for (Map.Entry<Integer, String> employee : employees.entrySet()) {
if(employee.getKey() > 30) {
linkedHashMap.put(employee.getKey(), employee.getValue());
}
}
System.out.println("Filtered Map: " + linkedHashMap);
Filtered Map: {35=Peter, 43=Luke, 31=John}
We’ll filter this map by keys and values and save the results in a
such as a
Use a
LinkedHashMap
which preserves the order of insertion
entrySet()
of the
employees
, and add each
employee
via its put() method. This works the same for the
implementation, but it will not preserve the order of insertion
LinkedHashMap
Map
,
HashMap
Iterate through the
Filtering a
Collection
by a
into a
HashMap
Value
Map<Integer, String> employees = new HasMap<>():
employees.put(35,
employees.put(29,
employees.put(43,
employees.put(31,
employees.put(25,
"Peter");
"Mark");
"Luke");
"John");
"James");
//filtering by value
Map<Integer, String> employeeOfTheMonth= new LinkedHashMap<>();
for (Map.Entry<Integer, String> employee : employees.entrySet()) {
if(employee.getKey() > "Peter") {
linkedHashMap.put(employee.getKey(), employee.getValue());
}
}
System.out.println("The employee of the Month: " + employeeOfTheMonth);
The employee of the Month: {35=Peter}
Collections and the Generic Framework
11
Filtering out by values basically is the same approach, instead of checking for
the key, we will check using the values instead
Collections and the Generic Framework
12
Intro to GUI
Course
ICS2606 | Computer Programming II
Date
@April 26, 2023
Module
Module 9
Mode
Synchronous
If-Task
Lecture
Progress
Not Started
Mastery
None
Sub-item
Resources
Last Study
Parent item
Due
-27 day(s)
Days Left
-28
Parent item 1
Section
Sub-item 1
Task Content
https://drive.google.com/file/d/1UPtFsunEDXzd2nr_ciVJBJkINZhllA9B/view?usp=sharing
Introduction
The
java.awt
package
Things to Consider in Building your GUI Application
Component
Buttons
TextFields
Label
Intro to GUI
1
Containers
Panel
Frames
Dialog
Layout Managers
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
Demonstrate how to nest layout managers to create complex layout
Create a
The
java.awt
SimpleCalculator
App
package
Abstract Window Toolkit
It is package in the Java API that allows us to create Graphical User Interface (GUI) objects like
buttons, frames, and text areas and the likes
First Generation GUI Toolkit: AWT
Second Generation GUI Toolkit: Swing
Third Generation GUI Toolkit: JavaFX
Intro to GUI
2
for
BoderLayout
FlowLayout
for
Window
Panel
- independent containers
- dependent containers
Things we need to consider in Building our GUI App
Components
Containers
Layout Managers
The
Frame
Class
The class
It uses
Frame
is a top level window with border and title bar
BorderLayout
as default layout manager
It has resizable corners
To terminate, press ^C for now
import java.awt.*;
public class SampleFrame{
private Frame f; //instantiation of top-level window to variable -> f
public SampleFrame() { //constructor - creates a new frame object everytime the constructor is called
f = new Frame("My first GUI App."); //title is always the same
Intro to GUI
3
}
public void startApp() {
f.setBackground(Color.PINK);
f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String[] args) {
SampleFrame sf = new SampleFrame(); //calls constructor to create a new frame
sf.startApp();
}
}
Used Methods:
void setBackground(Color bgColor)
//sets the background color of this window
void setSize(int width, int height)
//resizes this component so that is has width
//width and height height in pixels
void setVisible(boolean b)
//shows or hides this Window depending on the value
//of parameter b
A
Panel
inside a
Panel
Frame
- is a type of simple container that provides a space
It cannot be launched by itself, it needs to exist inside another container
the default layout manager for panel is the
FlowLayout
layout manager
import java.awt.*;
public class PanelInsideFrame {
//fields
private Frame f;
private Panel p;
//constructor
public PanelInsideFrame() {
f = new Frame("GUI App.");
p = new Panel();
}
public void startApp() {
//setting up the frame
f.setBackground(Color.CYAN);
f.setSize(400, 200);
Intro to GUI
4
//setting up the panel
p.setSize(100, 200);
p.setBackground(new Color(255, 100, 50));
//adding the panel into the frame
f.setLayout(null); //frame won't be using any layout managers - null
f.add(p);
f.setVisible(true);
}
public static void main(String[] args) {
PanelInsideFrame pan = new PanelInsideFrame();
pan.startApp();
}
}
Used Methods:
void setLayout(LayoutManger mgr)
//sets the layout manager for this container
void add(Component comp)
//appends the specified component to the end of
//this container
Layout Managers
Layout Managers are used to position our
Components
inside our
Containers
For complex layouts, we can also nest Containers to customize our layout manager
For AWT ( java.awt ) Package
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
For Swing ( javax.swing ) Package
BoxLayout
SpringLayout
The
FlowLayout
Manager
public class FlowLayout
extends Object
Intro to GUI
5
implements LayoutManager, Serializable
A flow layout arranges components in a directional flow much like lines of text in a paragraph
Flow layouts are typically used to arrange buttons in a panel. It arranges buttons horizontally
until no more buttons fit on the same line
The line alignment is determined by the align property
import java.awt.*;
public class FlowLayoutExample {
//Variable Fields
private Frame f;
private Button bAdd, bSub, bMul, bDiv;
public FlowLayoutExample() {
//creating the objects
f = new Frame("Flow Layout Example");
bAdd
bSub
bMul
bDiv
=
=
=
=
new
new
new
new
Button("+");
Button("-");
Button("*");
Button("/");
}
public void startApp() {
//setting up the objects
f.setLayout(new FlowLayout(FlowLayout.CENTER));
//When setting up a layout, we need to create a new object reference
f.add(bAdd);
f.add(bSub);
f.add(bMul);
f.add(bDiv);
//order of adding matters
f.setSize(200, 200);
f.setVisible(true);
}
public static void main(String[] args) {
//starting the app
FlowLayoutExample fle = new FlowLayoutExample();
fle.startApp();
}
}
The possible values are:
LEFT
RIGHT
CENTER
LEADING
Intro to GUI
6
TRAILING
Frame f = new Frame("This is a Window");
f.setLayout(new FlowLayout(FlowLayout.LEFT);
f.setLayout(new FlowLayout(FlowLayout.RIGHT);
f.setLayout(new FlowLayout(FlowLayout.CENTER);
f.setLayout(new FlowLayout(FlowLayout.LEADING);
f.setLayout(new FlowLayout(FlowLayout.TRAILING);
The
BorderLayout
Manger
public class BorderLayout
extends Object
implements LayoutManager2, Serializable
A border layout lays out a container, arranging and resizing its components to fit in five regions:
north, south, east, west, and center.
Each region may contain no more than one component, and is identified by a corresponding
constant: NORTH, EAST, WEST, and CENTER.
when trying the add more components to one region, it will follow through with the last line
of code
//Frame uses BorderLayout automatically
Frame f = new Frame("BorderLayoutTest");
f.add(new Button("One"), BorderLayout.SOUTH);
f.add(new Button("Two"), BorderLayout.SOUTH);
f.add(new Button("Three"), BorderLayout.SOUTH);
//this will create the button "Three" for the
//South position of the frame
As a convenience, BorderLayout interprets the absence of a string specification the same as
the constant CENTER
Panel p = new Panel();
p.setLayout(new BorderLayout());
//these are the same
p.add(new TextArea());
//as this
p.add(new TextArea(), BorderLayout.CENTER);
When adding a component to a container with a border layout, use one of these five constants,
for example
Intro to GUI
7
Panel p = new Panel();
p.setLayout(new BoderLayout());
p.add(new Button("Okay"), BorderLayout.SOUTH);
Example:
import java.awt.*;
public class BorderLayoutTest {
private Frame f;
private Button bN, bS, bC, bW, bE;
public BorderLayoutTest() {
f = new Frame("BorderLayout Test");
bN = new Button("North");
bS = new Button("South");
bC = new Button("Center");
bW = new Button("West");
bE = new Button("East");
}
public void startApp() {
//Frame uses BorderLayout by default
//Adding of Buttons
f.add(bN, BorderLayout.NORTH);
f.add(bS, BorderLayout.SOUTH);
f.add(bC, BorderLayout.CENTER);
f.add(bW, BorderLayout.WEST);
f.add(bE, BorderLayout.EAST);
f.setSize(200, 100);
f.setVisible(true);
f.setBackground(Color.PINK);
}
public static void main(String[] args) {
BorderLayoutTest blt = new BorderLayoutTest();
blt.startApp();
}
}
Used Methods:
void add(Component comp, Object constraints)
//adds the specified component to the end of
//the container. Also notifies the layout
//manager to add the component to this container's
//layout using the specified constraints object
The
GridLayout
Manager
The GridLayout class is a layout manager that lays out a container’s components in a
rectangular grid
Intro to GUI
8
The container is divided into equal-sized rectangles, and one component is placed to each
rectangle
When resized all components will still be equally sized
When both the numbers of rows and columns have been set to non-zero values, either by a
constructor or by the setRows and setColumns methods, the number of columns specified is
ignored
instead, the number of columns is determined from the specified number of rows and the
total number of components in the layout.
for example, if three rows and two columns have been specified and nine components are
added to the layout, they will display as three rows and three columns.
Specifying the number of columns affects the layout only when the number of rows is
set to zero
Example:
import java.awt.*;
public class GridLayoutTest {
private Frame f;
private Button b1, b2, b3, b4, b5, b6;
public GridLayoutTest() {
f = new Frame("Grid Layout Example");
b1
b2
b3
b4
b5
b6
=
=
=
=
=
=
new
new
new
new
new
new
Button("B1");
Button("B2");
Button("B3");
Button("B4");
Button("B5");
Button("B6");
}
public void startApp(){
GridLayout g = new GridLayout(3, 2);
f.setLayout(g);
//order of layout into frame
// left to right
// top to bottom
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.pack();
f.setSize(400, 200);
f.setVisible(true);
System.out.println(g.getColumns());
}
Intro to GUI
9
public static void main(String[] args) {
GridLayoutTest glt = new GridLayoutTest();
glt.startApp();
}
}
Customizing your Layout Manger
Before we start creating a custom layout manager, make sure that no existing layout manager
meets our requirements
In particular, layout managers such as
enough to work in many cases
GridBagLayout
,
SpringLayout
, and
BoxLayout
are flexible
We can also find layout managers from other sources, such as from the Internet
Finally, we can simply layout by grouping components into containers such as panels
Creating our First GUI APP
Containers:
Frame f
Components:
Label l1, l2, l3;
TextField tf1, tf2, tf3;
Button bAdd, bSub, bMul, bDiv, bClear;
In this type of application, it is best to use panels to customize our layout manager
Create four panels, use the default layout manager for the panels
Intro to GUI
p1
will contain
l1
and
tf1
p2
will contain
l2
and
tf2
10
p3
will contain
l3
and
tf3
Change the layout manager to Frame f, set the layout manager to
GridLayout(4, 1)
.
Add the panels to our frame
Intro to GUI
11
Event Handling Technique
Course
ICS2606 | Computer Programming II
Date
Module
Module 10
Mode
If-Task
Lecture
Progress
Not Started
Mastery
None
Sub-item
Resources
Last Study
Parent item
Due
Days Left
Parent item 1
Section
Sub-item 1
Task Content
https://drive.google.com/file/d/1bdx2ZJELjDxaPTwnh55sBhaMh6-TKa6q/view?u
sp=sharing
Introduction
Event Handling Technique
1
Fundamentals of Event Handlers
Event Handling Techniques
The Delegation Model
The Listener Interface
Adapter Classes
Inner Classes
Anonymous Classes
The Use of Lambda Classes
Applying Event Handling Techniques to apply functionality to our
SimpleCalculator App
Fundamental Event Handling Concepts
What are Events?
Events are objects that describe what happens
Events may be a button click, a mouse pass-over, a keyboard short cut or
any interaction to a GUI component
What are Event Sources?
Event sources are GUI components in which the user invoked an
interaction
Event sources have methods that allow you to register event listeners with
them. When an event happens to the source, the source sends a
notification of that event to ALL the listener objects that were registered
for that event
As one would expect in an object-oriented language like Java, the
information about the event is encapsulated in an event object.
in Java, all event object ultimately derive from the class
java.util.EventObject
Of course, there are subclasses for each event type, such as
ActionEvent
Event Handling Technique
and
WindowEvent
2
Different event sources can product different kinds of events.
For example, a button can send
can send WindowEvent objects
ActionEvent
objects, whereas a window
An event source is an object that can register listener objects and send
them event objects
The event source sends out event objects to all registered listeners when
that event occurs
The listener objects will then use the information in the event object to
determine their reaction to the event
What are Event Handlers?
An event handler is a method that is invoked every time that an event is
called
This is where you code the behavior you want to do every time an event
occurs
Event Handling Techniques
The Event Delegation Model
it allows you to delegate the event handler to a different class, thus
providing a loosely coupled GUI and Event Handler package
Each class will be a separate Java source file
You can create as many event handlers as you want, the important thing
after creating them is to register them for them to be used
Event Handling Technique
3
The Use of Listeners - Listeners are interfaces, once you implement an
interface, you are required to override ALL the methods in the interface
Category
Interface Name
Methods
Action
ActionListener
actionPerformed(ActionEvent)
Item
ItemListerner
itemStateChange(ItemEvent)
Mouse
MouseListener
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)
Mouse motion
MouseMotionListener
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
Key
KeyListener
KeyPressed(KeyEvent)
KeyReleased(KeyEvent)
KeyTyped(KeyEvent)
Focus
FocusListener
focusGained(FocusEvent)
focusLost(FocusEvent)
Adjustment
AdjustmentListener
adjuctmentValueChanged(AdjustmentEvent)
Component
ComponentListener
componentMoved(ComponentEvent))
componentHidden(ComponentEvent)
Event Handling Technique
4
Category
Interface Name
Methods
componentResized(ComponentEvent))
componentShown(ComponentEvent)
Window
WindowListener
windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
Container
ContainerListerner
componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
Text
TestListener
textValueChanged(TextEvent)
The Use of Adapter Classes
There are situations when it is better to adapter classes rather listeners
Not all listeners have corresponding adapter class, only listeners that
contain two or more methods have a corresponding adapter class
For example, if you will implement
WindowListner
you are required to
override all 7 methods even if you only need one, if that is the case, it is
better to use the
WindowAdapter
instead
private class MyCloseButtonHandler extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
Category
Mouse
Adapter Class
MouseAdapter
Methods
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
Event Handling Technique
5
Category
Adapter Class
Methods
mouseExited(MouseEvent)
mouseClicked(MouseEvent)
Mouse motion
MouseMotionAdapter
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
Key
KeyAdapter
KeyPressed(KeyEvent)
KeyReleasedd(KeyEvent)
KeyTyped(KeyEvent)
Focus
FocusAdapter
focusGained(FocusEvent)
focusLost(FocusEvent)
Component
ComponentAdapter
componentMoved(ComponentEvent)
componentHidden(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
Window
WindowAdapter
windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
Container
ContainerAdapter
componentAdded(ContainerEvent)
componentRemoved(ContaierEvent)
The Use of Inner Classes
The purpose of inner classes is used to make tightly coupled components.
As for the GUI apps, it is used to group the UI code and event handler
codes together in a single code base
public class SimpleCalculator implements ActionListener {
... ... ...
private class MyCloseButtonHandler extends WindowAdapter {
public void windowClosing(WindowEvent we) {
Event Handling Technique
6
System.exit(0);
}
}
... ... ...
}
The Use of Anonymous Classes
Anonymous classes are used to create an on-the-fly object that are
anonymous. There are event objects that does not have any handler or
object references
There event objects are created to that you can access and execute their
corresponding event handlers after which they are automatically destroyed
which leaves your memory at an optimized state
Usually, anonymous classes are used for mobile devices or desktop
application that you would like to have an efficient runtime, if you have less
objects in the memory, then you have an efficient runtime
f.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
String s = "Mouse dragging: X = " + e.getX() +
" Y = " + e.getY();
tf.setText(s);
}
}); // <- note the closing parenthesis
Use of Lambda Expression
The Lambda expression was introduced in Object Oriented Programming
— Module 5: Other Class Features
it allows you to pass unnamed functions as parameters to methods
It is a simplified version of anonymous classes in implementing event
handling technique
take note that this only works with functional interfaces (Interfaces with only
one abstract method — like ActionListener)
Event Handling Technique
7
Syntax:
(parameters) -> {
function body
}
With A Single Statement
b.addActionListener(
e -> System.out.println("Handled by Lamda Expression")
);
With Multiple Statements:
b.addActionListener(
e -> {
System.out.println("My Event Handler");
System.out.println("Handled by Lambda Expression");
}
);
Using Lambda with non functional interface
f.addWindowListener( e -> System.exit(0));
Event Handling Technique
8
Event Handling Technique
9
Building a Swing Desktop App
Course
Date
ICS2606 | Computer Programming II
@May 3, 2023
Module
Module 11
Mode
Synchronous
If-Task
Lecture
Progress
Not Started
Mastery
None
Sub-item
Resources
Last Study
Parent item
Due
-20 day(s)
Days Left
-21
Parent item 1
Section
Sub-item 1
Task Content
https://drive.google.com/file/d/1RkzdEDrKUvBFdYCyz0_HLmjTpq9QO85p/view?
usp=sharing
Introduction
Building a Swing Desktop App
1
The Swing Extension
AWT vs Swing
A simple swing application
JCheckBox
JRadioButton
JComboBox
JList
JLabel
Revisiting the package statement
Packaging your application to a JAR File
Creating an Executable GUI app using JAR
The Swing Extension
Java Swing Package is a part of Java Foundation Classes (JFC) that is used to
create window-based applications
The Swing Package is built on the top of AWT (Abstract Window Toolkit)
Unlike AWT, Java Swing provides a set of platform-independent and lightweight
components
The
javax.swing
JTextField
,
package provides classes for java swing API such as
JTextArea
,
JRadioButton
,
JCheckBox
,
JColorChooser
JButton
,
etc.
AWT vs Swing
Java AWT
Java Swing
AWT components are
platform-dependent
Java swing components are platform-independent
AWT components are
heavyweight
Swing components are lightweight
AWT does not support
pluggable look and feel
Swing supports pluggable look and feel
Building a Swing Desktop App
2
Java AWT
Java Swing
AWT provides less
Swing provides more powerful components such as Labels,
components than Swing
lists, scrollpanes, colorchooser, tabbedpane etc.
AWT does not follow MVC
Framework
Using
Swing follows MVC
JCheckBox
An implementation of check box — an item that can be selected or deselected,
and which displays its state on the user
By convention, any number of check boxes in a group can be selected
A click can turn it on (select) or off (deselect)
Using
JRadioButton
An implementation of radio button — an item that can be selected or
deselected, and which displays its state to the user
Used with ButtonGroup object to create a group of buttons in which only one
button at a time can be selected
Using
JComboBox
A component that combines a button or editable and a drop-down list
The user can select a value from the drop-down list, which appears at the user’s
request
If you make the combo box editable, then the combo box includes an editable
field into which the user can type a value
Using
JList
A component that displays a list of object and allows the user to select one or
more items
A separate model,
Creating a
JList
ListModel
, maintains the contents of the list
means first creating a list model then populating that list model
with data elements
You can think of a list model as a holder of items, and the
displayer
Building a Swing Desktop App
JList
as the
3
A Simple Swing App — Converting your AWT
SimpleCalculator
App to a
SwingApp
It is suggested that a package declaration be added in our source code in
preparation for the creation of the JAR File
Add “J” in front of the Components and Containers, do not add it in your Layout
Managers
Compiling files onto a new directory
//in src folder
javac ../<directoryName> demo/<javaFile>.java
//Example
javac ../finalLocation demo/SwingDemo.java
The JAR File
A JAR (Java ARchive) is a package file format typically used to group java
classes into one file for distribution
It is very similar to a ZIP file
It can be accessed and used in different Operating Systems
There are two (2) ways on how to create a Jar File
1. Without a Manifest File
To create:
jar cvf <JarFile.jar> <Files>
ie:
jar cvf JarFile.jar *
to run
java -cp <JarFile.jar> <fullyQualifiedName>
Building a Swing Desktop App
4
ie:
java -cp SimpleSwingProj1.jar demo.SimpleSwingCalculator
2. With Manifest file, AKA the Executable Jar File
to create:
jar cvfm <JarFile.jar> <manifestFile> <Files>
ie:
jar cvf MyJar2.jar manif.txt *
to run:
java -jar <JarFile.jar>
ie:
java -jar SimpleSwingProj2.jar
A manifest file looks like this:
Main-Class: demo.SimpleSwingCalculator <PRESS THE ENTER KEY>
Building a Swing Desktop App
5
Formative Assessments (Finals)
Module 7 - File I/O
1. Which of the following classes is not a part of the
java.io
package?
Buffer
2. Which import statement MUST be present if you are going to use the Scanner class in your code
import java.util.Scanner;
3. By default, the
readLine()
method of the
BufferedReader
class can accept _____ values
a. String
b. int
c. any data type
d. char
4. When accepting a user input using the Scanner class what type of Exception object will be seen if the
user does not enter the correct value for a variable’s data type?
a.
InputMismatchException
b.
IOException
c.
IllegalArgumentException
d.
NumberFormatException
5. Which class is used under the
a.
FileInputStream
b.
FileRead
c.
FileInputStreamReader
d.
FileInputReader
java.io
package that is used to gain a read access to a binary file
6. Which two are value (choose two).
Given
is a reference to a valid
f
java.io.File
instance
fr
is a reference to a valid
java.io.FileReader
br
is a reference to a valid
java.io.BufferedReader
-
instance
instance
FileReader fr2 = new FileReader(fr);
BufferedReader br2 = new BufferedReader(f);
File f2 = new File(f)
FileReader fr2 = new FileReader(br);
Formative Assessments (Finals)
1
- FileReader fr2 = new FileReader(f);
- BufferedReader br2 = new BufferedReader(fr);
7. Which code, inserted at line 36, will loop through a text file and output a line at a time from the text
field?
Given:
is a reference to a valid
f
java.io.File
instance
fr
is a reference to a valid
java.io.FileReader
br
is a reference to a valid
java.io.BufferedReader
34.
35.
36.
37.
38.
instance
instance
String line = null;
//insert code here
System.out.println(line);
}
- while((line = fr.readLine()) != null) {
- while((line = br.readLine()) != null) {
- while((line = f.read()) != null) {
- while((line = f.readLine()) != null) {
- while((line = br.read()) != null) {
Module 8 - Collections and Generic Framework
1. Assume that the main method is in a valid Java source file and all the needed import statements are
provided, what will be the result of the code below?
public static void main(String args[]) {
Set set = new TreeSet();
set.add(10);
set.add("20");
set.add(30);
Iterator it = set.iterator();
while(it.hasNext())
System.out.print(it.next() + " ");
}
The given code will compile but a
RuntimeException
will occur
2. Implementing the Comparable interface will allow objects of that class to be sorted, which package can
we find the Comparable interface
java.lang
package
3. Which of the following is a reason to use an
Formative Assessments (Finals)
ArrayList
instead of an array
2
An
ArrayList
resizes itself as necessary when items are added but an array does not
4. Which of the following statements IS NOT TRUE?
Objects in a Map can have duplicate keys
5. Which of the following statements is NOT TRUE?
Objects from a user-defined class that DOES NOT implement any interface can be sorted because
they inherit the Object Class
6. Assume that the main method is in a valid Java source file and all the needed import statements are
provided, which of the following statements is TRUE?
public static void main(String args[]) {
Set<Object> s = new HashSet<Object>();
s.add("java");
s.add(new String("java"));
System.out.println(s);
}
7. Which, inserted independently at line 9, will compile?
import java.util.*;
class Beta extends Alpha {
public static void go(Set<Alpha> set) {}
public static void main(String[] args) {
Set<Alpha> setA = new TreeSet<Alpha>();
Set<Beta> setB = new TreeSet<Beta>();
Set<Object> setO = new TreeSet<Object>();
//insert code here
}
}
class Alpha {}
The code fragments:
s1.go(setA);
s2.go(setB);
s3.go(setO);
8. What is the result of the output of the given code?
Consider the given code below:
import java.util.*;
class TestMeNow {
public static void main(String[] args) {
Object a = new LinkedList();
Object b = new TreeSet();
Object c = new TreeMap();
System.out.prin((a instanceof Collection) + ", ");
System.out.prin((b instanceof Collection) + ", ");
Formative Assessments (Finals)
System.out.prin((a instanceof Collection) + ", ");
3
System.out.prin((c instanceof Collection) + ", ");
}
}
9. Assume that the main method is in a valid Java source file and all the needed import statements are
provided, what will be the result of the code below?
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<String>();
if(ts.add("oracle "))
if(ts.add("java "))
if(ts.add("oracle ")
ts.add("java ");
for(String s : ts)
System.out.print(s);
}
Module 9: Introduction to GUI
1. How to you indicate where a component will be positioned using
a. Do nothing, the
FlowLayout
Flowlayout
will position the component
b. Assign a row/column grid reference
c. North, South, East, West
d. Pass a X/Y percentage parameter to the add method
2. The AWT in
java.awt
package stands for
Abstract Window Toolkit
3. How could you set the frame surface color to pink? Given the following code:
import java.awt.*;
public class SetF extends Frame{
public static void main(String argv{}) {
SetF s = new SetF();
s.setSize(300, 200);
s.setVisible(true);
}
}
a.
s.setBackground(Color.pink);
b.
s.Background(pink);
c.
s.color = Color.pink
d.
s.setColor(PINK);
4. How do you change the current layout manager for a container
Formative Assessments (Finals)
4
a. Use the
setLayout
method
b. Once created you cannot change the current layout manager of a component
c. Use the
updateLayout
method
d. Use the
setLayoutManager
method
5. Components are GUI objects that you can see visually. A subclass of Components is the Container
class; the Container objects are GUI components where you can put GUI components inside. Which of
the following is a Container object?
a.
Frame
b.
Button
c.
TextArea
d.
TextField
6. What best describes the appearance of an application with the following code?
import java.awt.*;
public class FlowAp extends Frame{
public static void main(String[] args) {
FlowAp fa = new FlowAp();
fa.setSize(400, 300);
fa.setVisible(true);
}
FlowAp() {
add(new
add(new
add(new
add(new
}
Button("One"));
Button("Two"));
Button("Three"));
Button("Four"));
}
a. A
Frame
with one large button marked Four in the Centre
b. A
Frame
with buttons marked One to Four one each edge
c. A
Frame
with buttons marked One to four running from the top to bottom
d. An Error at runtime indicating you have not set a
LayoutManager
Module 10 : Event Handling
1. What do you call the object that refers to the interaction between the user and the GUI Component?
a. Event Listeners
b. Event Handlers
c. Adapter Classes
d. Events
Formative Assessments (Finals)
5
2. Which of the following TRUE about Event Handlers?
a. Event Handlers are the method invoked when an event is
triggered.
b. Event Handlers are ALWAYS within the same code where
your GUI components are.
c. Event Handlers represent the interaction between the user
and the GUI components.
d. Event Handlers are objects that send out event objects to all registered listeners when that event
occurs.
3. If event handling classes needs to be used in your program, you need to import what Java package?
a.
java.awt
package
b.
javax.awt.events
c.
javax.events
d.
java.awt.event
package
package
package
4. Which of the following DOES NOT generate an Event Object?
a. Clicking a button
b. Inspecting the contents of a Frame object
c. Typing in a text area
d. Pressing the enter key in a text field
5. Which of the following IS NOT a Listener interface
a.
MouseMotionListener
b.
MouseListener
c.
ActionListener
d.
MouseAdapter
6. What will happen when you attempt to compile and run this code
//Demonstration of event handling
import java.awt.*;
import java.awt.event.
public class MyWc extends Frame implements WindowListener {
public static void main(String [] args) {
MyWc mwc = new MyWc();
}
public void windowCIosing(WindowEvent we) {
System.exit(0);
} //End of windowClosing
setSize(300,300);
setVisible(true);
Formative Assessments (Finals)
6
}
//End of class
a. Visible Frame created that that can be closed
b. Compilation but no output at runtime
c. Error at compile time
d. Error at compile time because of comment before import
statements
7. What keyword should we use for the code snippet below?
private class MyEventHandler _____ WindowAdapter
{ //some codes here }
a. extends
b. implements
c. override
d. Overload
Module 11: Building a Swing Desktop App
1. Which of the following IS NOT TRUE about Swing Components?
a. Swing Components are light weight components.
b. Swing components are platform-independent
c. Swing supports pluggable look and feel components.
d. Swing provides less components compared with AWT
2. What do you call the special file that can contain information about the files packaged in a JAR file?
a. class file
b. Executable File
c. Java Source File
d. manifest file
3. Which Swing component is an implementation of a radio button that can select or deselect an item
which is used with a
ButtonGroup
object to create a group of buttons in which only one item at a time
can be selected?
a.
JList
b.
JCheckbox
Formative Assessments (Finals)
7
c.
JRadioButton
d.
JComboBox
4. What does JAR stand for?
a. Java ARchive
b. Java Archive Resource
c. Java Application Resource
d. Java Automatic Resource
5. What package should you import if you want to use the Swing
Framework?
a.
java.awt.swing
b.
java.awt
c.
javax.swing
d.
java.swing
package
package
package
package
Formative Assessments (Finals)
8
Long Test 3
1. Which of the following statements IS NOT TRUE?
a. Objects in a Map can have duplicate keys
2. Given the code snippet, which of the following declaration when inserted in the line
// insert code here will NOT ensure the output: [aaa, bbb, ccc]
//insert code here
myStr.add("aaa");
myStr.add("ccc");
myStr.add("bbb");
System.out.println(myStr);
a.
Set<String>myStr = new HashSet<String>();
3. What is the output of the following code segment?
List cities = new ArrayList();
cities.add("Manila");
cities.add("Malabon");
for(int i = 1; i < cities.size(); i++) cities.add(i, "+");
System.out.println(cities);
a. No output because the program goes into an infinite loop
4. Given the main method
public static void main(String args[]) {
Set<Object> s = new HashSet<Object>();
s.add("java");
s.add(new String("java"));
System.out.println(s);
}
Assume that the main method is in a valid Java Source file and all the needed
import statements are provided, which of the following statements is TRUE?
Long Test 3
1
a. The code will compile and run and will print “java” as the output
5. Which of the following is a reason to use an
ArrayList
instead of an array
a. an ArrayList resizes itself as necessary when items are added but an array
does not
6. Consider the given code below, What is the result of the output of the given code?
import java.util.*;
class TestMeNow {
public static void main (String args[]) {
Object a = new LinkedList();
Object b = new TreeSet();
Object c = new TreeMap();
System.out.print((a instanceof Collection)+",");
System.out.print((b instanceof Collection)+",");
System.out.print((c instanceof Collection));
}
}
a. true, true, false
7. What is the result?
import java.util.*;
class Stuff implements Comparable {
int x;
Stuff(int x) { this.x = x; }
public int compareTo(Object o) { return 0; }
}
class AddStuff {
public static void main(String[] args) {
TreeSet<Stuff> ts = new TreeSet<Stuff>();
ts.add(new Stuff(1));
ts.add(new Stuff(2));
System.out.println(ts.size());
}
}
a. 1
8. Which of the following is NOT TRUE
a. Objects from a user-defined class that DOES NOT implement any interface can
be sorted because they inherit the Object class
Long Test 3
2
9. Assume that the main method is in a valid source file and all the needed
public static void main(String args[]) {
TreeSet<String> ts = new TreeSet<String>();
if(ts.add("oracle "))
if(ts.add("java "))
if(ts.add("oracle "))
ts.add("java ");
for (String s : ts)
System.out.print(s);
}
a. oracle java
10. Which, inserted at line 9, will cause the output “abc”?
Given:
import java.util.*;
class ForInTest {
static List list = new ArrayList();
public static void main(String[] args) {
list.add("a");
list.add("b");
list.add("c");
//insert code here
System.out.print(o);
}
}
a.
for(Object o : list)
11. Which import statement MUST be present if you are going to use the Scanner class
in your code?
a.
import java.util.Scanner;
12. Which class is used under the java.io package that is used to gain a read access to
a binary file
a.
FileInputStream
13. Which code, insert at line 36, will loop through a text file and output a line at a time
form the text field?
Long Test 3
3
Given:
f is a reference to a valid
java.io.File
fr is a reference to a valid
br is a reference to a valid
instance
java.io.FileReader
instance
java.io.BufferedReader
instance
String line = null
//insert code here
System.out.print(line)
}
a.
while((line = br.readLine()) != null {
14. Which of the following classes is not part of the java.io package?
a. Buffer
15. Consider the following
RandomArray
class, which represents the correct /* code to
add integer to array */
public class RandomArray
{
private ArrayList<Integer> randArray;
public RandomArray() { randArray = getArray(); }
/** @return list with random Integers from 0 to 100 inclusive */
{
System.out.println("How many integers? ");
int arrayLength = IO.readlnt(); //read user input
ArrayList<Integer> array = new ArrayList<Integer>();
for (int i = 0; i < arrayLength; i++)
/* code to add integer to array *\
return array;
}
/** Print all elements of this array. */
public void printArray() { ... }
}
a.
array.add(new Integer(Math.random() * 101));
16. Let
Long Test 3
mylist
be an
ArrayList<String>
containing these elements:
4
[”Jimmy”, “Marc”, “Harris”, “Leo”, “Frank”]
Which of the following statements will cause an error to occur?
a.
list.set(3, new Integer(6));
b.
String x = list.get(5);
17. Given the Code below, what is the result?
import java.util.*;
class TestScanner {
public static void main(String[] args) {
String str = "oracle, java, 1995";
Scannner sc = new Scanner(str);
while (sc.hasNext())
System.out.print(sc.next() + "");
}
}
a. oracle, java, 1995
18. Which two are value (choose two).
Given
is a reference to a valid
f
java.io.File
instance
fr
is a reference to a valid
java.io.FileReader
br
is a reference to a valid
java.io.BufferedReader
-
instance
instance
FileReader fr2 = new FileReader(fr);
BufferedReader br2 = new BufferedReader(f);
File f2 = new File(f)
FileReader fr2 = new FileReader(br);
- FileReader fr2 = new FileReader(f);
- BufferedReader br2 = new BufferedReader(fr);
19. Given the code below with line numbers for reference purposes, which of the
statements is INCORRECT?
import java.io.*;
class WriteFile {
Long Test 3
5
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new FileWriter("myfile.txt));
String str;
while((str = br.readLine()) != null) {
out.println(str)
}
out.close();
br.close();
}
}
a. if the code executed more than once, myfile.txt will continue to append the values
that the user enters
20. Which, inserted independently at line 9, will compile?
import java.util.*;
class Beta extends Alpha {
public static void go(Set<Alpha> set) {}
public static void main(String[] args) {
Set<Alpha> setA = new TreeSet<Alpha>();
Set<Beta> setB = new TreeSet<Beta>();
Set<Object> setO = new TreeSet<Object>();
//insert code here
}
}
class Alpha { }
And the tree code fragments
s1.go(setA):
s2.go(setB):
s3.go(setO);
a. only s1
21. When accepting a user input Scanner class what type Exception object will be seen
if the user does not enter the correct value for a variable’s data type
a.
InputMismatchException
22. By default, the
readLIne()
method of the
BufferedReader
class can accept _______
values.
Long Test 3
6
a. String
23. What is the output of the following code segment assuming that the code segment
below belongs to a valid Java source file?
import java.util.ArrayList;
import java.util.List;
...
List<Integer> list = new ArrayList <Interger>();
for(int i = 0; i <= 7; i++) list.add(new. Integer(i));
for(int i = 0; i < list.size(); i++) list.remove(i);
for(Integer x : list) System.out.print(x + " ");
a. 1 3 5 7
24. Implementing the Comparable interface will allow objects of that class to be sorted,
which package can we find the Comparable interface?
a.
java.lang
package
25. Assume that the main method is in a valid Java source file and all the needed
import statement are provided, what will be result of the code below?
public static void main(String args[]) {
Set set = new TreeSet();
set.add(10);
set.add("20");
set.add(30);
Iterator it = set.iterator();
while (it.hasNext())
System.out.print(it.next() + " ");
}
a. The given code will compile but a
Long Test 3
RuntimeException
will occur
7
Long Test 4
1. How could you set the frame surface color to pink? Given the following code:
import java.awt.*;
public class SetF extends Frame{
public static void main(String argv{}) {
SetF s = new SetF();
s.setSize(300, 200);
s.setVisible(true);
}
}
a.
s.setBackground(Color.pink);
b.
s.Background(pink);
c.
s.color = Color.pink
d.
s.setColor(PINK);
2. Which of the following TRUE about Event Handlers?
a. Event Handlers are the method invoked when an event is triggered
3. What do you call the special file that can contain information about the files
packaged in a JAR file
a. manifest file
4. How do you indicate where a component will be positioned using
a. Do nothing, the
FlowLayout
will position the component
5. Which of the following layout managers IS NOT a part of the
a.
Flowlayout
java.awt
package
BoxLayout
6. How do you change the current layout manger for a container
a. Use the
setLayout
method
7. What most closely matches the appearance when this code runs
Long Test 4
1
import java.awt.*;
public class CompLay extends Frame {
public static void main(String argv[]) {
CompLay cl = new CompLay();
}
CompLay(){
Panel p = new Panel();
p.setBackground(Color.pink);
p.add(new Button("One"));
p.add(new Button("Two"));
p.add(new Button("Three"));
add("South", p);
setLayout(new FlowLayout());
setSize(300, 300);
setVisible(true);
}
}
a. The buttons will run from right along the top of the frame
8. You have created a non-executable JAR file called MyJar.jar. The test class is
located in classes\myFolder\MyTestClass.class You created the JAR file while inside
the classes folder.
Which of the following command is the correct way of running the said JAR file?
a.
java -cp MyJar.jar myFolder.MyTestClass
9. What keyword should we use for the code snippet below?
private class MyEventHandler _______ WindowAdapter
{
//some code here
}
a. extends
10. What best describes the appearance of the application with the following code?
import java.awt.*;
public class FlowAp extends Frame{
public static void main(String[] args) {
FlowAp fa = new FlowAp();
Long Test 4
2
fa.setSize(400, 300);
fa.setVisible(true);
}
FlowAp() {
add(new
add(new
add(new
add(new
}
Button("One"));
Button("Two"));
Button("Three"));
Button("Four"));
}
a. A Frame with one large button marked Four in the Center
11. Which of the following IS NOT TRUE about Swing?
a. You can find Frame, the Button and the Label classes under the
package
javax.swing
12. What package should you import if you want to use the Swing Framework?
a.
javax.swing
package
13. You are planning to create an executable JAR file, your test class is under the
classes \myFolder\MyTestClass.class
Your current folder (your present working directory) is in
classes\
.
Which of the following command will allow you to create an executable JAR file
assuming you have the correct file named
a.
manif.mf
in the same folder (classes)
jar cvfm MyJar.jar manif.mf *
14. Which of the following IS NOT TRUE about Swing Components?
a. Swing provides less components compared with AWT
15. Components are GUI objects that you can see visually. A subclass of Components
is the Container class; the Container objects are GUI components where you can
put GUI components inside. Which of the following is a Container object?
a. Frame
16. What Swing component displays a list of objects and allows the user to select one
or more items, this will also require you to have a ListModel that will maintain the
Long Test 4
3
contents of the list the user can choose from
a.
JList
17. Which of the following DOES NOT generate an Event Object
a. Inspecting the contents of a Frame Object
18. What does JAR stand for
a. Java ARchive
19. What will be displayed when you attempt to compile and run the following code?
//Code start
import java.awt.*;
public class Butt extends Frame {
public static void main(String argv[]) {
Butt MyButt = new Butt();
}
Butt() {
Button HelloBut = new Button("Hello");
Button ByeBut = new Button("Bye");
add(HelloBut);
add(ByeBut);
setSize(300, 300);
setVisible(true);
}
}
//Code end
a. One button occupying the entire frame saying Bye
20. which of the following IS NOT a Listener Interface
a.
MouseAdapter
21. What will happen when you attempt to compile and run this code?
//Demonstration of event handling
import java.awt.*;
import java.awt.event.*;
public class MyWc extends Frame implements WindowListener{
public static void main(String[] args) {
Long Test 4
4
MyWc mwc = new MyWc();
}
public void windowClosing(WindowEvent we) {
System.exit(0);
} //end of windowClosing
public void MyWc() {
setSize(300, 300);
setVisible(true);
}
} //End of class
a. Error at compile time
22. Which of the following operator should we use when using the Lambda Expression
as your event handling technique?
a.
->
23. Which Swing component is an implementation of a radio button that can select or
deselect and item which is used with a ButtonGroup object to create a group of
buttons in which only one item at a time can be selected?
a.
JRadioButton
24. If event handling classes needs to be used in your program, you need to import
what java package?
a.
java.awt.event
package
25. Which of the following is NOT needed when youu build your GUI App
a. File
26. Which of the following is NOT a valid GUI / Event package that we can import
a.
java.swing.*;
27. Which of the following is an abstract class found in the
a.
java.awt.event package
MouseAdapter
28. Which of the following package you SHOULD import if you want to use the
GridLayout class
a.
Long Test 4
java.awt.*
5
29. Which of the following is the best Event Handling strategy for event handlers that
you want to reuse for multiple GUI components
a. Delegating your event handler to a different Java Source code
30. What do you call the object that refers to the interaction between the user and the
GUI Component
a. Events
Long Test 4
6
Download