Introduction to Java Programming 2020
Introduction to Java Programming 2020
PROGRAMMING
SESSION 1
SESSION OUTLINE
• What Java is: Features & Strengths
• Common Programming Errors
• Good Programming Practice
• Java comments
• Java Installation & Configuration
– Using Windows Environment
– Using NetBeans IDE
• Java Program Structure with examples
• Lab Work
Historical Account
• Sun Microsystems in 1991 funded an internal
corporate research project code-named
Green, which resulted in a C++-based
language
• Its creator, James Gosling, called Oak after an
oak tree outside his window at Sun.
• The name was later changed to Java
Features/Strengths
• Java is a high-level programming language
– It implements most of the concepts of objects-
oriented systems e. g. software reuse.
– It is platform-independent
– It is more portable. It will run on any PC that
implements the Java virtual machine.
• Java has “class libraries
• Java can be implemented by Integrated
Development Environments.
Java & C++
• It has built-in graphical interface support
• Its syntax (structure) is similar to C++, but
simpler than C++ in most areas
• Java Software Development Kit (SDK) is open
source. Java SDK is software for compiling and
running Java programs.
• Java has many of the features of C++.
• It is slower than its ‘rival’ C++ because of extra
level of processing.
• It uses no pointers
Java Platforms
• There are three main platforms.
• Java Standard Edition: used for developing
desktop applications;
• Java Enterprise Edition: used to produce
software for businesses and enterprises
• Java Micro Edition: used for smart devices such
as mobile phones, smartphones, personal digital
assistants (PDAs).
Types of Java Programs
• Java Applications
– Must have the resource files stored locally
– Run directly on a device
– Contain a "main()" method and compiled using the
"javac",
• Java Applets
– Run by a browser and no "main()" method
– They are contained within a website document: HTML
– They are stored on the server of a website
– They are unable to run standalone.
• Midlets Run on mobile phones and managed by device
software.
• Servlets are designed to run inside web servers
Common Programming Error
• Forgetting one of the delimiters. A syntax error
occurs when the compiler encounters code that
violates Java’s language rules
• Java is case sensitive. Not using the proper
uppercase and lowercase letters for an identifier
1. 2x + 5y – 7
class ExpCal1{
public static void main(String[] args)
{
int x= 2, int y= 3 , int results;
results= 2*x + 5*y -7;
System.out.println("The output of the program
is:"+ results);
}
}
Problem Analysis
class OperatorPrecedence {
Lab Activity 1
1. Write a program to find difference between
two numbers
2. Write a program to find the product of two
numbers
Identify Errors and Fix Them
}
import java.util.Scanner;
public class Addition
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int num1, num2, sum;
num1 = input.nextInt();
num2 = input.nextInt();
}
APPLICATIONS
1. Write a program to find the smallest of two
numbers.
}
};
Logical Operators
Logical Operators
• Logical operators are symbols that are used to
combine expressions containing relational
operators.
• This circumstance will arise when you want to
perform a statement block on a combined
condition,
• like x > 7 and y < 14.
• Then you code this using an AND operator.
The AND operator is represented as &&.
Logical Operators
Logical Operators
• Example:
((x > 7) && (x < 14))
(salary >=4000 && salary <=5000)
Decision Making statements
• if -else statement
• Java else if is a like doing another if condition for a true or false value.
Syntax:
if(condition)
{
//execute your code
}
else if(condition n)
{
//execute your code
}
else
{
//execute your code
}
Application
public class Compare {
if (b > a) {
System.out.println("b is greater");
}
else if(a > b){
System.out.println("a is greater");
}
else {
System.out.println("Both are equal");
}
}
}
Java switch Statements
• Java switch statement is used when you have multiple possibilities for the if
statement.
• Syntax:
switch(variable)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;
default:
//execute your code
break;
}
Example:
public class Sample {
switch (a) {
case 1:
System.out.println("You chose One");
break;
case 2:
System.out.println("You chose Two");
break;
case 3:
System.out.println("You chose Three");
break;
Switch statement
case 4:
System.out.println("You chose Four");
break;
case 5:
System.out.println("You chose Five");
break;
default:
System.out.println("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
}
END
Looping statements
• For loop
• While loop
• Do-while loop
Looping using ‘for’ statement
for (initial statement; termination condition;
increment instruction)
statement ;
• For multiple statements the statements are put
inside brackets.
for (initial statement; termination condition;
increment instruction)
{
statement 1;
statement 2;
}
Lab Application
// This program uses for loop to print numbers 1 through 10
to standard output
class PrintNum
{
public static void main(String[] args)
{
int i;
for(i=1; i<11; i++)
{
System.out.println(“The numbers are: " + i);
}
}
}
Error identification and Correction
int j, sum;
sum = 0;
for (j=1;j<=10;j++) ;
sum += j ;
Java while loop
QUESTION
A student must pass both Mid-Sem and
examination to pass a course. The pass marks
for each is 50%. Write a program to input the
two marks and determine whether or not the
student passed.
Lab Activities
1. Write a program to print all the prime
numbers between 20 and 40.
2. Write a program to determine the maximum
value of two numbers
NewDay
SESSION OUTLINE
• Arrays
• Types of array
– One dimensional array
– Multidimensional array
• Declaring Array
• Applications
• Lab Activity
Array
• A data structure that can store a fixed size of
sequential collection of elements of same data
type
• Syntax:
– datatype[] identifier;
or
– datatype identifier[];
Example:
int[] refVar;
Illustration of array in Memory
Array Declaration
• To use array, the following are required:
• Declare a variable to be used as the array name
E.g. string [] mySelf;
char[] grade;
short[] refVar;
first part: string [].
• A bit different from creating a regular variable,
notice square brackets.
• That means that we want to create an string
array, and not a single variable.
Lab Activity
• Declare two integer arrays
• Declare two double arrays
• Declare three char arrays
• Declare one long arrays
• Arrays can be initialized at declaration time:
• int age[5]={22,25,30,32,35};
Initialize an Array in Java
• Using the initializer list. Thus, declare,
construct and initialise the array all in one
statement.
int age[5]={22,25,30,32,35};
stuff[0] = 23;
stuff[1] = 38;
stuff[2] = 7*2;
}
GradeTable
• The grade for student 0 week 1 is 42
• The grade for student 3 week 4 is 93
• The grade for student 6 week 2 is 78
• A compact notation for specifying a cell uses the
row and column indexes like this:
gradeTable[ row ][ col ]
• As with one dimensional arrays, indices start at
zero. For example:
gradeTable[ 0 ][ 1 ] is 42
Lab Activity
Write the values that will be output by the
following:
• gradeTable[ 3 ][ 4 ]
• gradeTable[ 6 ][ 2 ]
• gradeTable[ 5 ][ 2 ]
• gradeTable[ 2 ][ 3 ]
• int value = (gradeTable[ 6 ][ 2 ] + 2) / 2 ;
• gradeTable[ 3 ][ 4 ]++ ;
Lab Assignment
Declare and initialize an array for this table
Lab Assignment 2
• Write a program to display the following
values from the table:
• 100
• 43
• 73
Using Initializer list
double[][] sales = {
{8.2, 2.5, 5.4},
{81.2, 92.5, 45.4},
{20.2, 22.5, 85.4},
};
2D String Implementation
class ArrayString {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. ", "Miss "},
{"Afriyie", "Patricia", "Agnes"}
};
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][1]);
System.out.println(names[0][3] + names[1][2]);
}
}
Arrays Implementation Using LOOPS
• for loop
Lab Exercise
Write a program to print out the unit of Toothpaste
sold on Thursday, Monday and Friday.
2D Array
class SalesTable{
public static void main(String[] args) {
int[][]examTable={
{60,76,62,52,67},
{64,53,84,55,48},
{90,46,76,100,73}
};
//int examTable,sum;
int sum=examTable[2][1] + examTable[2][2] +
examTable[2][3]+examTable[2][4];
System.out.println("The total score for Zuleha is:" + sum);
System.out.println("ICT for Alima is:" + examTable[0][1]);
System.out.println("Social Studies for Alima is:" +
examTable[0][3]);
}}
2D Array
int [][]SalesTable = {
{40, 10, 120, 70, 67},
{46, 53, 84, 18, 48},
{90, 46, 76, 100, 73},
{78, 79, 48, 50, 45},
{81, 59, 84, 92, 66} };
for(int i = 0; i <=4; i++){
for(int j = 0; j <=4; j++){
if (i==4)
if (j!=1)
System.out.println("sales = " + SalesTable[i][j]);
}
}
NEXT LESSON
Quiz on Reading Assignment
Attempt all questions
Duration: 5 Minutes
1. Name two java classes that can be used in an
interactive program
2. What is the function of the next() method
3. What method is used to convert the text
enters by a user to the appropriate primitive
type?
[ 5 Marks]
SESSION OUTLINE
1. Instance variables
2. Class variables
3. Local variables
Instance Variables
• Variables declared outside the method definitions are
called instance variables.
• Generally they are defined immediately after the first line
of the class definition.
• An instance variable represents data for which each
instance has it's own copy
class MyPoint {
int x;
int y;
// method 1
// method 2
}
Class variable
• The static keyword is used to declare a class
variable.
class MyPoint {
int x;
int y;
static int quadrant=1;
// method 1
// method 2
}
Local Variables
• Variables defined within the methods are called local
variables. Their scope is limited to within the method in which
they are defined.
class MyPoint {
int x, y;
static int quadrant;
public void displayPoint( ) {
int temp;
int j;
}
}
The variables temp and j are local variables.
They are valid only within the method displayPoint( ).
Methods
• A set of actions taken by a receiving object in
response to a request/message
• Methods are defined as follows
– Return type
– Name of the method
– A list of parameters
– Body of the method.
• void displayPoint( ) {
// body of the method
}
Methods
• The method describes the mechanisms that
actually perform its tasks.
• The method hides from its user the complex
tasks that it performs.
• A method is a mechanism that knows how
objects of a certain type carry out a particular
task.
• It tells us about the behaviour of objects.
Methods
• In Java, we begin by creating a class to house a
method,
• just as a car’s engineering drawings house the
design of an accelerator pedal.
• In a class, you provide one or more methods that
are designed to perform the class’s tasks.
• For example, a class that represents a bank
account might contain
– one method to deposit money to an account
– another method to withdraw money from an account
– a third to inquire what the current balance is.
Method calling in a Program
public class Javamethods {
void corona(){
System.out.print("This is a deadly disease,");
System.out.println("observe all the safety
protocols.");
}
void exams(){
System.out.println("Exams are starting on Monday,
the 27th of July.");
System.out.println("The first paper is Java
Programming.");
int bankacct(){
int deposit=500,withdrawal=150, accbalance;
accbalance=deposit-withdrawal;
System.out.println(" Your Account Balance is " +
accbalance);
return accbalance;
}
public static void main(String[] args) {
Javamethods methods = new Javamethods();
methods.corona();
methods.exams();
methods.bankacct();
}
Defining a Class
import java.util.Date;
class Date{
public static void main(String args[]) {
Date today = new Date(); //instantiate object
System.out.println(today);
}
}
Detail
• The first line in the Date application listing above
begins a class definition block.
• A class--is a template that describes the data and
behaviour associated with instances of that class.
When you instantiate a class you create an object
that will look and feel like other instances of the
same class.
• The data associated with a class or object are
called variables; the behaviour associated with
class or object are called methods.
Methods implementation 2
System.out.println(add(x,y));
System.out.println(add(m,n));
System.out.println(add(s1,s2));
}
}
Concept of Inheritance of OOP
• The process where one class acquires the
properties (methods and fields) of another.
• The class which inherits the properties of
other is known as subclass (derived class)
• The class whose properties are inherited is
known as superclass (base class, parent class).
General Syntax
• extends Keyword
• extends is the keyword used to inherit the properties of a
class.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Concept of Inheritance
• Deriving a new class from the existing class
Public class Cat extends Animal {
Public void meow(){ //method
System.out.println(“The cat said meow”);
}
}
The cat class inherits is derived from the Animal
class. The Animal class is called superclass
The cat class is called subclass or derived class
Concept of Inheritance
class Calculation{
int z;
public void addition(int x, int y){
z = x+y;
System.out.println("The sum of the given numbers:"+z);
}
public void Substraction(int x, int y){
z = x-y;
System.out.println("The difference between the given
numbers:"+z);
}
}
Concept of Inheritance
class My_Calculation extends Calculation{
public void multiplication(int x, int y){
z = x*y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]){
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b);
}}
Method Overriding
• Overriding means to supersede the
functionality of an existing method.
• If a class inherits a method from its superclass,
then there is a chance to override the method
provided that it is not marked final.
• Overriding helps to define a behavior that is
specific to the subclass type.
• Thus, a subclass can implement a parent class
method based on its requirement.
Rules about method overriding
• The argument list should be exactly the same as that of
the overridden method.
• The return type should be the same or a subtype of the
return type declared in the original overridden method
in the superclass.
• The access level cannot be more restrictive than the
overridden method's access level. For example: If the
superclass method is declared public then the
overridding method in the sub class cannot be either
private or protected.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden .
Method overriding
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
} }
Method Overriding
class Lecturer{
Void showMessage(){
System.out.println(“I am in lecturer class”);
}
void display(){
System.out.println(“Inside lecturer’s display() ”)
}
Class Student extends Lecturer{
void display(){
System.out.println(“Inside student’s display()”);
{
Public static void main(String [] args){
Student object = new Student();
Object.display();
}
}
Lab Exercise
Write programs to illustrate how the following
are implemented in Java
1. Method
2. Inheritance
3. Method Overloading
4. Method Overriding
Inheritance
SESSION OUTLINE
• Java as Object Oriented Programming Language
• Multiple Inheritance
• Packages
• Access modifiers
• Applet and Graphics
– Applet program
• HTML
• Lab Applications
Multiple Inheritance
• Java does not support multiple inheritance
• we cannot inherit from more than one class at
the same time.
• Two classes:
class a
class b
Inheritance concept:
• Example: class a, b // not possible in Java
• But possible in Java rival?
class a, b
{
……………..
……………
} // not possible in Java. Illegal
Multiple Inheritance Cont’d
• Want to inherit the class child from mother and
father classes.
• That is subclass child from two super classes:
• Class mother, Class father
class Child extends Father, Mother
{
// body of class child
}
• Syntax error
• Use the concept of interface
Interface
• An interface is a collection of methods.
• Interfaces serve to implement multiple
inheritance
• Implementing classes implement the
methods.
Interface Declaration
• Syntax:
• Interface interface –name
• The interface is created using the keyword
interface
• Interface can be declared public
• An interface can extend any number of
interfaces
Programming implementing the concept of interface
class Salary{
void showSalary(){
System.out.println("Salary:10000");
}
// Interface defined
interface Commission {
void showComm(); // only method declared
}
class Income extends Salary implements Commission {
public void showComm(){
System.out.println("Commission:1000");
}}
void showIncome(){ // method defined
showSalary(); // method of salary class called
showComm(); // method of commission class called
}
Interface Implementation Cont’d
public static void main (String [] args)
{
Income obj = new Income(); // objected created
obj.showIncome(); // method called using object
System.out.println("Total income includes ");
}
}
interface Birth {
default void run(){
System.out.println("I am sitting, mum ");
System.out.println("I am running, kid !!");
}
}
interface Crawl {
default void run(){
System.out.println("I am crawling, daddy ");
}
}
class Parent implements Birth, Crawl {
public static void main(String[] args) {
Parent self = new Parent();
self.run();
}
Interface Implementation
import java.applet.Applet;
import java.awt.Graphics;
public class AppletProgram extends Applet
{
public void paint(Graphics g)
{
g.drawString("Big Java", 25,25);
}
}
HTML SCRIPT
<html>
<body>
<Applet code = "AppletProgram" width = 150
height = 100>
</Applet>
</body>
</html>
Applet Programming
// Applet programming
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("Java Programmer can used Java to create two types of java programs", 27,37);
g.drawString("An applet is a java program run by a Java-enabled web browser or an applet viewer", 20,50);
}
}
HTML Code to Run Applet
<html>
<body>
<Applet code = "JavaApp.class" width = 250
height = 200>
</Applet>
</body>
</html>
Drawing Lines Using Applet
import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g ) {
g.setColor( Color.green );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
}
}
}
HTML FILE TO RUN APPLET
<html>
<body>
<Applet code = "DrawingLines.class" width =
250 height = 200>
</Applet>
</body>
</html>
Lab Exercise
Write an applet to draw 15 lines on a yellow
background
Applet Implementation
// Drawing red Lines applet
import java.applet.*;
import java.awt.*;
public class DrawingRedLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g ) {
g.setColor( Color.red );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
}
}
}
// Draw red lines
<html>
<body>
<Applet code = "DrawingRedLines.class" width = 250 height = 200>
</Applet>
</body>
</html>
Applet Application 1
//This program produces applet
import java.awt.*;
import java.applet.Applet;
}
HTML Script
<html>
<head>
<title> My Page</title>
</head>
<body>
<h2>This page shows use of Applet</h2>
<p><applet code =“MyAppletTest.class" width= 300 height =
100>
</applet>
<hr>
</body>
</html>
Applet application 2
// Lifecycle of an applet
import java.applet.Applet;
public class LifeCycle extends Applet{
<HTML>
<Body>
<Applet code = "HelloWorldWar.class"
width = 600 height = 300>
</Applet>
</Body>
</HTML>
Applet Application 3
// The applet using Java
import java.applet.*;
import java.awt.*;
public class TestApplet extends Applet {
public void paint(Graphics g) {
g.drawString(“Welcome to my Page",10,10);
}
}
HTML to run the applet
<HTML>
<head>
<title> My page </title>
</head>
<Body>
<h2> This page shows the use of applet </h2>
<Applet code = " TestApplet.class" width = 600
height = 300>
</Applet>
</Body>
</HTML>
HTML and APPLET
<html>
<head>
<title>The Java Applet</title>
</head>
<body>
<H1>Welcome to the JAVA Applet!</H1>
<applet width=300 height=300
code="DrawingLines.class">
</applet>
</body>
</html>
• public class DrawingLines extends Applet {
•
• int width, height;
• public void init() {
• width = getSize().width;
• height = getSize().height;
• setBackground( Color.black );
• }
•
• public void paint( Graphics g ) {
• g.setColor( Color.green );
• for ( int i = 0; i < 10; ++i ) {
• g.drawLine( width, height, i * width / 10, 0 );
• }
• }
• }
<html>
<head>
<title>The Java Applet</title>
</head>
<body>
<H1>Welcome to the JAVA Applet!</H1>
<applet width=300 height=300
code="DrawingLines.class"> </applet>
Sorry, your browser isn’t able to run Java applets.
</body>
</html>
Graphics
• Graphics class provides a method drawString
to display text.
• It also requires a position to be specified as
arguments.
END
import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.blue );
}
}
Drawing Lines
public class DrawingLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g ) {
g.setColor( Color.red );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
} }
}
• The HelloWorld applet shown next is a Java class that displays the string "Hello World".
• Following is the source code for the HelloWorld applet:
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class HelloWorld extends JApplet { //Called when
this applet is loaded into the browser.
public void init() { //Execute a job on the event-
dispatching thread; creating this applet's GUI. try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JLabel lbl = new JLabel("Hello World");
add(lbl);
} });
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
} }}
//Here's the source code for an applet:
import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g ) {
g.setColor( Color.green );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
} }
SESSION OUTLINE
• Java Foundation Classes
• Creating Graphical User Interface
• Application of Graphical User Interface
Java Foundation Classes (JFC)
• A group of features to help people build
graphical user interfaces (GUIs).
• A GUI is an interface between a user and a
computer that makes use of input devices
other than the keyboard, and presentation
techniques other than alphanumeric
• The JFC is defined as containing the following
features:
Java Abstract Windowing Toolkit
• java.awt: Contains all of the classes for
creating user interfaces and for painting
graphics and images. E.g.: Button, TextArea,
Window
How to Display Components
• Containers are the objects that are displayed
directly on the screen. Example: JFrame
• Controls must be added to a container if you
want to see them.
• The container, JFrame will be the main
window of most of the swing applications.
The GUI Builder's windows
Components
• The IDE's GUI Builder solves the core problem
of Java GUI creation by streamlining the
workflow of creating graphical interfaces,
freeing developers from the complexities of
Swing layout managers.
• Design Area
• Palette
• Properties Window
• Navigator
Design Area.
• This is the GUI Builder's primary window for
creating and editing Java GUI forms.
• The toolbar's Source button enables you to
view a class's source code,
• The Design button allows you to view a
graphical view of the GUI components,
• The History button allows you to access the
local history of changes of the file.
• The additional toolbar buttons provide
convenient access to common commands
Palette Window
• A customizable list of available components
containing tabs for JFC/Swing, AWT, and
JavaBeans components, as well as layout
managers.
• In addition, you can create, remove, and
rearrange the categories displayed in the
Palette using the customizer.
Java Palette Tools
• The palette contains a number of useful tools for
designing GUI
• Swing Containers: Panel, Frame, Toolbar, etc.
• Swing Controls: Button, Checkbox, Text Field, Text
Area, etc
• Swing Menus: Menu bar, Popup Menu, Menu,
etc.
• Swing Windows: Dialog box, File Chooser, Color
Chooser, etc
• AWT: A Label, Text Field, List, Text Area, etc.
Properties Window
• Displays the properties of the component
currently selected in the GUI Builder,
Navigator window, Projects window, or Files
window.
Navigator
• Provides a representation of all the
components, both visual and non-visual, in
your application as a tree hierarchy.
• The Navigator also provides visual feedback
about what component in the tree is currently
being edited in the GUI Builder as well as
allows you to organize components in the
available panels.
Free Design
• In the IDE's GUI Builder, you can build your
forms by simply putting components where
you want them as though you were using
absolute positioning.
• The GUI Builder figures out which layout
attributes are required and then generates the
code for you automatically.
• You need not concern yourself with insets,
anchors, fills, and so forth.
Automatic Component Positioning
(Snapping)
• The GUI Builder provides visual feedback that
assists in positioning components as you add
components to a form,
• The GUI Builder provides helpful inline hints
and other visual feedback regarding where
components should be placed on your form,
• Automatically snapping components into
position along guidelines.
• Visual Feedback
Visual Feedback
• The GUI Builder provides visual feedback
regarding component anchoring/fixing and
chaining relationships.
• These indicators enable you to quickly identify
the various positioning relationships and
component
• This speeds the GUI design process, enabling
you to quickly create visual interfaces that
work.
Creation of Some Components
• Text Field/ JText Field: An area of the screen
where one can enter a line of text or for
editing a single line of text.
• Codes to create TextFields
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
BUTTON (OK)
A labelled button
Code to create buttons:
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
• Close a window
Exit = new javax.swing.JButton();
Application of GUI
import java.awt.*;
public class GUI extends Frame {
public GUI (String s){
super(s);
setBackground(Color.yellow);
setLayout(new FlowLayout());
Button pushButton = new Button("press me");
add(pushButton);
}
public static void main(String[] args) {
GUI screen = new GUI ("Example 1");
screen.setSize(500, 100);
screen.setVisible(true);
} }
EVENT
• An Event is an action which occurs when a GUI
component changes its state.
• Examples:
• When a button is pressed
• When an item is selected in a list, event is generated.
• Events are handled through interfaces
public class GUI extends Frame implements
ActionListener {
ActionListener Interface
• The interface ActionListener is contained in
the package java.awt.event.
• Therefore we should import java.awt.event
into the application as
import java.awt.event;
• This interface contains a method:
• public void actionPerformed(ActionEvent
event) {
Implementation
import java.lang.*;
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Lab Activity
public class SleepMessage {
public static void main(String args[])
throws InterruptedException {
String importantInfo[] = {
"The student sleeps in the class",
"Does he eat too much heavy food?",
"Majority of students eat little food before lectures",
"So you also eat little too" };
for (int i = 0;
i < importantInfo.length; i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
System.out.println(importantInfo[i]);
} }
}
public class TwoThreads {
public static class Thread1 extends Thread {
public void run() {
System.out.println("A");
System.out.println("B");
}}
public static class Thread2 extends Thread {
public void run() {
System.out.println("1");
System.out.println("2");
}}
public static void main(String[] args) {
new Thread1().start();
Threads and Java language
• Create a thread by instantiating an object of
type Thread (or a subclass) and send it
the start() message.
• A program can send the start() message to any
object that implements the Runnable interface.
Threads and Java language
• The definition of each thread's behavior is
contained in its run() method.
• A run method is equivalent to main() in a
traditional program: a thread will continue
running until run() returns, at which point the
thread dies or terminated.
Output
• We have no idea in what order the lines will
execute, except that "1" will be printed before "2"
and "A" before "B." The output could be any one
of the following:
• 12AB
• 1A2B
• 1AB2
• A12B
• A1B2
• AB12
Two threads to do work
• One for timing and one to do actual work.
• The main thread calculates prime numbers
• It creates and starts a timer thread
• Which will sleep for ten seconds, and then
set a flag that the main thread will check.
• After ten seconds, the main thread will stop.
Two threads to do work
// CalculatePrimes -- calculate as many primes as we can in ten seconds
public class CalculatePrimes extends Thread {
public static final int MAX_PRIMES = 1000000;
public static final int TEN_SECONDS = 10000;
public volatile boolean finished = false;
public void run() {
int[] primes = new int[MAX_PRIMES];
int count = 0;
for (int i=2; count<MAX_PRIMES; i++) {
// Check to see if the timer has expired
if (finished) {
break; }
boolean prime = true;
for (int j=0; j<count; j++) {
if (i % primes[j] == 0) {
prime = false;
break;
}}
if (prime) {
primes[count++] = i;
System.out.println("Found prime: " + i);
} }}
public static void main(String[] args) {
CalculatePrimes calculator = new CalculatePrimes();
calculator.start();
try {
Thread.sleep(TEN_SECONDS);
}
catch (InterruptedException e) {
// fall through
}
calculator.finished = true;
}}
End
• The definition of each thread's behavior is
contained in its run() method.
• A run method is equivalent to main() in a
traditional program: a thread will continue
running until run() returns, at which point the
thread dies or terminated.