dise - windows based application development in java
TRANSCRIPT
Diploma in Software Engineering
Module VI: Windows Based Application Development in Java
Rasan SamarasingheESOFT Computer Studies (pvt) Ltd.No 68/1, Main Street, Pallegama, Embilipitiya.
Contents1. Introduction to Java2. Features of Java3. What you can create by Java?4. Start Java Programming5. Creating First Java Program6. Java Virtual Machine7. Basic Rules to Remember8. Keywords in Java9. Comments in Java Programs10. Printing Statements11. Primitive Data Types in Java12. Arithmetic Operators13. Assignment Operators14. Comparison Operators15. Logical Operators16. If Statement17. If… Else Statement18. If… Else if… Else Statement19. Nested If Statement20. While Loop21. Do While Loop22. For Loop23. Reading User Input
24. Arrays25. Two Dimensional Arrays26. Strings27. Objects and Classes28. Java Classes29. Java Objects30. Methods with Return Value31. Methods without Return Value32. Constructors33. Method Overloading34. Variable Types35. Inheritance36. Method Overriding37. Abstract Classes38. Interfaces39. Polymorphism40. Packages41. Access Modifiers42. Encapsulation43. Exceptions44. JDBC45. GUI Applications with Swing46. NetBeans IDE
Introduction to Java
• Developed by Sun Microsystems (has merged into Oracle Corporation later)
• Initiated by James Gosling• Released in 1995• Java has 3 main versions as Java SE, Java EE
and Java ME
Features of Java
Object Oriented Platform independent Simple Secure Portable Robust Multi-threaded Interpreted High Performance
What you can create by Java?
• Desktop (GUI) applications• Enterprise level applications• Web applications• Web services• Java Applets• Mobile applications
Start Java Programming
What you need to program in Java?
Java Development Kit (JDK)Microsoft Notepad or any other text editorCommand Prompt
Creating First Java Program
public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}
MyFirstApp.java
Java Virtual Machine (JVM)
Java Virtual Machine (JVM)
1. When Java source code (.java files) is compiled, it is translated into Java bytecodes and then placed into (.class) files.
2. The JVM executes Java bytecodes and run the program.
Java was designed with a concept of write once and run anywhere. Java Virtual Machine plays the
central role in this concept.
Basic Rules to Remember
Java is case sensitive…
Hello not equals to hello
Basic Rules to Remember
Class name should be a single word and it cannot contain symbols and should be started
with a character…
Wrong class name Correct way
Hello World HelloWorld
Java Window Java_Window
3DUnit Unit3D
“FillForm” FillForm
public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}
Basic Rules to Remember
Name of the program file should exactly match the class name...
Save as MyFirstApp.java
Basic Rules to Remember
Main method which is a mandatory part of every java program…
public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}
Basic Rules to Remember
Tokens must be separated by WhitespacesExcept ( ) ; { } . [ ] + - * / =
public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}
Keywords in Java
Comments in Java Programs
Comments for single line
// this is a single line comment
For multiline
/* this is a multilinecomment*/
Printing Statements
System.out.print(“your text”); //prints text
System.out.println(“your text”); //prints text and create a new line
System.out.print(“line one\n line two”);//prints text in two lines
Primitive Data Types in Java
Keyword Type of data the variable will store Size in memory
boolean true/false value 1 bit
byte byte size integer 8 bits
char a single character 16 bits
double double precision floating point decimal number 64 bits
float single precision floating point decimal number 32 bits
int a whole number 32 bits
long a whole number (used for long numbers) 64 bits
short a whole number (used for short numbers) 16 bits
Variable Declaration in Java
Variable declarationtype variable_list;
Variable declaration and initializationtype variable_name = value;
Variable Declaration in Java
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Arithmetic Operators
Operator Description Example+ Addition A + B will give 30
- Subtraction A - B will give -10
* Multiplication A * B will give 200
/ Division B / A will give 2
% Modulus B % A will give 0
++ Increment B++ gives 21
-- Decrement B-- gives 19
A = 10, B = 20
Assignment Operators
Operator Example
= C = A + B will assign value of A + B into C
+= C += A is equivalent to C = C + A
-= C -= A is equivalent to C = C - A
*= C *= A is equivalent to C = C * A
/= C /= A is equivalent to C = C / A
%= C %= A is equivalent to C = C % A
Comparison Operators
Operator Example
== (A == B) is false.
!= (A != B) is true.
> (A > B) is false.
< (A < B) is true.
>= (A >= B) is false.
<= (A <= B) is true.
A = 10, B = 20
Logical Operators
Operator Name Example
&& AND (A && B) is False
|| OR (A || B) is True
! NOT !(A && B) is True
A = True, B = False
If Statement
if(Boolean_expression){ //Statements will execute if the Boolean
expression is true}
If Statement
Boolean Expression
Statements
True
False
If… Else Statement
if(Boolean_expression){ //Executes when the Boolean expression is
true}else{ //Executes when the Boolean expression is
false}
If… Else Statement
Boolean Expression
Statements
True
False
Statements
If… Else if… Else Statement
if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true}else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true}else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true}else { //Executes when the none of the above condition is true.}
If… Else if… Else Statement
Boolean expression 1
False
Statements
Boolean expression 2
Boolean expression 3
Statements
Statements
False
False
Statements
True
True
True
Nested If Statement
if(Boolean_expression 1){ //Executes when the Boolean expression 1 is
true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is
true }}
Nested If Statement
Boolean Expression 1
True
False
StatementsBoolean Expression 2
True
False
While Loop
while(Boolean_expression) { //Statements}
While Loop
Boolean Expression
Statements
True
False
Do While Loop
do { //Statements}while(Boolean_expression);
Do While Loop
Boolean Expression
Statements
True
False
For Loop
for(initialization; Boolean_expression; update) { //Statements}
For Loop
Boolean Expression
Statements
True
False
Update
Initialization
Nested Loop
Boolean Expression
True
False
Boolean Expression
Statements
True
False
Reading User Input by the Keyboardimport java.io.*;
public class DemoApp{public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter your text: “);String txt = br.readLine();System.out.println(“You have entered:” + txt);}}
Arrays
10 30 20 50 15 35
0 1 2 3 4 5
Size = 6
Element Index No
An Array can hold many values in a same data type under a single name
A single dimensional array
Building a Single Dimensional Array
// Creating an ArrayDataType[] ArrayName = new DataType[size];
// Assigning valuesArrayName[index] = value;ArrayName[index] = value;……..
Building a Single Dimensional Array
char[] letters = new char[4];
letters[0] = ‘a’;letters[1] = ‘b’;letters[2] = ‘c’;letters[3] = ‘d’;
0 1 2 3
a b c d
0 1 2 3
letters
letters
Values in an Array can access by referring index number
Building a Single Dimensional Array
//using an array initializerDataType[] ArrayName = {element 1, element 2,
element 3, … element n}
int[] points = {10, 20, 30, 40, 50}; 10 20 30 40
0 1 2 3
points
50
4
Manipulating Arrays
Finding the largest value of an Array
Sorting an Array
15
50
35
25
10
2
1
5
4
3
1
2
3
4
5
Two Dimensional Arrays
10 20 30
100 200 300
0 1 2
0
1
int[][] abc = new int[2][3];
abc[0][0] = 10;abc[0][1] = 20;abc[0][2] = 30;abc[1][0] = 100;abc[1][1] = 200;abc[1][2] = 300;
Rows Columns
Column Index
Row Index
Strings
• String is a sequence of characters• In java, Strings are objects.• Strings have been given some features to be
looked similar to primitive type.
String <variable name> = new String(“<value>”);orString <variable name> = “<value>”;
Useful Operations with Strings
• concat()• length()• charAt(<index>)• substring(int <begin index>, int <end index>)• trim()• toLowerCase() • toUpperCase()
Java Objects and Classes
Java Classes
Method
Dog
namecolor
bark()
class Dog{
String name;String color;
public Dog(){}
public void bark(){System.out.println(“dog is barking!”);}
}
Attributes
Constructor
Java Objects
Dog myPet = new Dog(); //creating an object //Assigning values to AttributesmyPet.name = “Scooby”; myPet.color = “Brown”;
//calling methodmyPet.bark();
Methods
Method is a group of statements to perform a specific task.
• Methods with Return Value• Methods without Return Value
Methods with Return Value
public int max(int num1, int num2){int result;if (num1 > num2){result = num1;}else{result = num2;}return result;}
Access modifierReturn typeMethod name
parameters
Return valueMethod body
Methods without Return Value
public void print(String txt){System.out.println(“your text: “ + txt)}
Access modifierVoid represents no return valueMethod name
parameter
Method body
Constructors
• Each time a new object is created the constructor will be invoked
• Constructor are created with class name
• There can be more constructors distinguished by their parameters
class Dog{String name;
public Dog(String name){this.name = name;}
}
//creating an object from Dog classDog myDog = new Dog(“brown”);
Constructor
String Parameter
String Argument
Method Overloading
public class Car{
public void Drive(){System.out.println(“Car is driving”);}
public void Drive(int speed){System.out.println(“Car is driving in ” + speed + “kmph”);}
}
Variable Types
Variables in a Class can be categorize into three types
1. Local Variables2. Instance Variables3. Static/Class Variables
Local Variables
• Declared in methods, constructors, or blocks.
• Access modifiers cannot be used.
• Visible only within the declared method, constructor or block.
• Should be declared with an initial value.
public class Vehicle{int number;String color;static String model;
void Drive(){int speed = 100;System.out.print(“vehicle is driving in “ + speed + “kmph”);}
}
Instance Variables
• Declared in a class, but outside a method, constructor or any block.
• Access modifiers can be given.• Can be accessed directly
anywhere in the class. • Have default values. • Should be called using an
object reference to access within static methods and outside of the class.
public class Vehicle{int number;String color;static String model;
void Drive(){int speed = 100;System.out.print(“vehicle is driving in “ + speed + “kmph”);}
}
Static/Class Variables
public class Vehicle{int number;String color;static String model;
void Drive(){int speed = 100;System.out.print(“vehicle is driving in “ + speed + “kmph”);}
}
• Declared with the static keyword in a class, but outside a method, constructor or a block.
• Only one copy for each class regardless how many objects created.
• Have default values. • Can be accessed by calling
with the class name.
Inheritance
class Vehicle{//attributes and methods}
class Car extends Vehicle{//attributes and methods}
class Van extends Vehicle{//attributes and methods}
Vehicle
Car Van
Method Overriding
class Vehicle{public void drive(){System.out.println(“Vehicle is driving”);}}
class Car extends Vehicle{public void drive(){System.out.println(“Car is driving”);}}
Abstract Classes
• abstract key word makes the class as abstract.
• Abstract classes can not be instantiated.
• Abstract classes are intended to be extended.
• Abstract classes may have abstract methods.
• Abstract methods has no body.
• Abstract methods should be overridden.
abstract class Animal{int age;
public void sleep(){}
public abstract void makeNoise();
}
public class Cat extends Animal{
public void makeNoise(){System.out.print(“meow”);}
}
Interfaces
• An interface contains a collection of abstract methods that a class implements.
• Interfaces states the names of methods, their return types and arguments.
• There is no body for any method in interfaces.
• A class can implement more than one interface at a time.
interface Vehicle{public void Drive(int speed);public void Stop();}
public class Car implements Vehicle{
public void Drive(int kmph){System.out.print(“Vehicle is driving in ” + kmph + “kmph speed”);}
public void Stop(){System.out.print(“Car stopped!”);}
}
Polymorphismclass Animal{public void Speak(){}}
class Cat extends Animal{public void Speak(){System.out.println(“Meow");}}
class Dog extends Animal{public void Speak(){System.out.println(“Woof");}}
class Duck extends Animal{public void Speak(){System.out.println(“Quack");}}
Animal d = new Dog();Animal c = new Cat();Animal du = new Duck();
d.Speak();c.Speak();du.Speak();
Packages
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations) providing access protection and namespace management.
//At the top of your source codeimport <package name>.*;import <package name>.<class name>;
academic
Creating and Importing Packages
package academic;
public class school{public void display(){System.out.println(“School!”);}}
package academic.esoft;
public class dise{public void display(){System.out.println(“dise!”);}}
import academic.esoft.*;
public class myApp{public static void main(String[] args){dise ob = new dise();ob.display();}}
esoft
Access Modifiers
Access Modifiers
Same class
Same package Sub class Other
packages
public Y Y Y Y
protected Y Y Y N
No access modifier Y Y N N
private Y N N N
Encapsulationclass student{
private int age;
public int getAge(){return age;}
public void setAge(int n){age = n;}
}
Data
Input OutputMethod Method
Method
Exceptions
An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, like:
• A user has entered invalid data.• A file that needs to be opened cannot be found.• A network connection has been lost in the
middle of communications
Exception Hierarchy
Throwable
Exception Error
IOException RuntimeException ThreadDeath
ArithmeticException NullPointerException ClassCastException
******
Exception Categories
• Checked exceptions: Cannot simply be ignored at the time of compilation.
• Runtime exceptions: Ignored at the time of compilation.
• Errors: Problems that arise beyond the control of the user or the programmer.
Handling and Throwing Exceptions
try { //Protected code } catch(ExceptionName var) { //Catch block } finally { //The finally block always executes}
public void Show() throws <ExceptionName> {throw new <ExceptionName>;}
You can…
handle Exceptionsby using try catch blocks
or
throw Exceptions
Declaring you own Exception
• All exceptions must be a child of Throwable.
• If you want to write a checked exception, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the RuntimeException class.
JDBC
A. What is JDBC?B. JDBC ArchitectureC. Creating JDBC ApplicationD. StatementsE. Statement Execute MethodsF. Types of Result SetsG. Result Set Methods
What is JDBC?
JDBC stands for Java Database Connectivity.It is a Java API for database-independent connectivity
between the Java application and a wide range of databases.
Making a connection to a database
Creating SQL statements
Executing that SQL queries in the database
Viewing & Modifying the resulting records
JDBC Architecture
This provides the application-to-JDBC Manager connection.
This class manages a list of database drivers.
This interface handles the communications with the database server.
Creating JDBC Application
The following steps are involved in creating a JDBC Application
1. Import the packages 2. Register the JDBC driver 3. Open a connection 4. Create a SQL query statement5. Execute a query 6. Extract data from result set 7. Clean up the environment
Creating JDBC Applicationimport java.sql.*; // import the packagespublic class DBApp{public static void main(String[] args){Connection conn = null;Statement stmt = null;ResultSet rs = null;try{Class.forName("com.mysql.jdbc.Driver"); // Register the JDBC driverconn = DriverManager.getConnection("jdbc:mysql://localhost/Student","root“,“1234"); // Open a connectionstmt = conn.createStatement(); // Create a SQL query statementrs = stmt.executeQuery("select * from Student"); // Execute a querywhile(rs.next()){ // Extract data from Result SetSystem.out.print("ID: "+ rs.getInt("ID"));System.out.print(“, Name: "+ rs.getString(“name"));System.out.println(“, Address: "+ rs.getString(“address"));}rs.close(); // Clean up the environment stmt.close();conn.close();}catch(Exception ex){}}}
1
234
5
6
7
Statements
Statement stmt = conn.createStatement( ); stmt.execute(“DELETE * FROM Student”);
PreparedStatement pstmt = conn.prepareStatement(“DELETE FROM Student WHERE id = ?");pstmt.setInt(1, 100);pstmt.execute();
CallableStatement cstmt = conn.prepareCall ("{call getStName (?, ?)}");cstmt.setInt(1, st_ID);cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);cstmt.execute();String stName = cstmt.getString(2);
Statement - Useful when using static SQL statements at runtime.
PreparedStatement - Accepts input parameters at runtime.
CallableStatement - Use to access database stored procedures.
Statement Execute Methods
• boolean execute(String SQL) : Returns a boolean value if a ResultSet object can be retrieved; otherwise, returns false.
• int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL statement.
• ResultSet executeQuery(String SQL) : Returns a ResultSet object.
boolean b = stmt.execute(“DELETE FROM Student WHERE id=12”);
int res = stmt.executeUpdate(“UPDATE Student SET name=‘Roshan’ WHERE id=15”);
ResultSet rs = stmt.executeQuery(“SELECT * FROM Student”);
Types of Result Sets
RSType RSConcurrency
ResultSet.TYPE_FORWARD_ONLY ResultSet.CONCUR_READ_ONLY
ResultSet.TYPE_SCROLL_INSENSITIVE ResultSet.CONCUR_UPDATABLE
ResultSet.TYPE_SCROLL_SENSITIVE
createStatement(int RSType, int RSConcurrency);
prepareStatement(String SQL, int RSType, int RSConcurrency);
prepareCall(String SQL, int RSType, int RSConcurrency);
Result Set MethodsNavigation Viewing
public void beforeFirst() public int getInt(String columnName)
public void afterLast() public int getInt(int columnIndex)
public boolean first()
public void last() Updating
public boolean absolute(int row) public void updateString(int columnIndex, String s)
public boolean relative(int row) public void updateString(String columnName, String s)
public boolean previous() public void updateRow()
public boolean next() public void deleteRow()
public int getRow() public void refreshRow()
public void moveToInsertRow() public void cancelRowUpdates()
public void moveToCurrentRow() public void insertRow()
GUI Development Using Swing
A. Introduction to SwingB. Swing Components HierarchyC. Creating a simple GUI ApplicationD. Using FrameE. Using LayoutsF. Using ButtonG. Using LabelH. Using Text FieldI. Using Radio ButtonJ. Creating MenusK. EventsL. How Events Handling Work?M. Dialog Box Methods
Introduction to Swing
Swing is the primary Java GUI widget toolkit. It is part of Oracle's Java Foundation Classes (JFC). It is an API for providing a graphical user interface (GUI) for Java programs.
Light WeightRich controlsHighly CustomizablePluggable look-and-feel
Swing Components Hierarchy
Creating a simple GUI Application
Creating a GUI Application is an Easy Process!
1. First, Make a Frame2. Then, Make a Component3. Add the Component to the Frame4. Display it!
Using Frame
JFrame f = new JFrame("GUI Application");f.setBounds(300,300,400,250);f.setVisible(true);
Using Layouts
f.setLayout(new FlowLayout()); f.setLayout(new GridLayout(2,3)); f.setLayout(new BorderLayout());
f.setLayout(null); f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
Flow Layout Grid Layout Border Layout
No Layout Box Layout
Using Button
JButton btnOK = new JButton("OK");btnOK.setBounds(140,80,100,25);f.getContentPane().add(btnOK);
Using Label
JLabel lblWelcome = new JLabel("Welcome");lblWelcome.setBounds(155,80,100,25);f.getContentPane().add(lblWelcome);
Using Text Field
JTextField txtInput = new JTextField();txtInput.setBounds(155,80,100,25);f.getContentPane().add(txtInput);
Using Radio Button
JRadioButton rdoCat = new JRadioButton("Cat", true);JRadioButton rdoDog = new JRadioButton("Dog");ButtonGroup grp = new ButtonGroup();grp.add(rdoCat);grp.add(rdoDog);rdoCat.setBounds(120,80,50,25);rdoDog.setBounds(180,80,50,25);f.add(rdoCat);f.add(rdoDog);
Creating MenusJMenuBar menubar = new JMenuBar(); //create Menu Bar//Create MenusJMenu filemenu = new JMenu("File");JMenu viewmenu = new JMenu("View"); JMenu aboutmenu = new JMenu("About");//Create Menu ItemsJMenuItem newMenuItem = new JMenuItem("New");JMenuItem openMenuItem = new JMenuItem("Open");JMenuItem saveMenuItem = new JMenuItem("Save");JMenuItem exitMenuItem = new JMenuItem("Exit");//Add Menu Items to Menusfilemenu.add(newMenuItem);filemenu.add(openMenuItem);filemenu.add(saveMenuItem);filemenu.addSeparator();filemenu.add(exitMenuItem);//Add Menus to Menu Barmenubar.add(filemenu);menubar.add(viewmenu);menubar.add(aboutmenu);//Add Menu Bar to the Framef.setJMenuBar(menubar);f.setVisible(true);
Menu
Menu Item
Menu Bar
Events
An event is when something special happens within a Graphical User Interface.
Things like buttons being clicked, the mouse moving, text being entered into text fields, the program closing, etc.. then an event will trigger.
How Events Handling Work?
Dialog Box Methods
//Displays a simple messagevoid JOptionPane.showMessageDialog(cmpnt, object, string, int, icon);
//Asks the user for confirmationint JOptionPane.showConfirmDialog(cmpnt, object, string, int, int, icon);
//Displays a prompt for inputtingString JOptionPane.showInputDialog(cmpnt, object, string, int);
Displaying Dialog BoxesJOptionPane.showMessageDialog(frame,"Eggs are not supposed to be
green.");
JOptionPane.showMessageDialog(frame,"Eggs are not supposed to be green.","Inane warning",JOptionPane.WARNING_MESSAGE);
JOptionPane.showMessageDialog(frame,"Eggs are not supposed to be green.","Inane error",JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(frame,"Eggs are not supposed to be green.","A plain message",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(frame,"Eggs are not supposed to be green.","Inane custom dialog",JOptionPane.INFORMATION_MESSAGE,icon);
NetBeans IDE
• An integrated development environment (IDE) for developing primarily with Java.
• Runs on most operating systems with a Java Virtual Machine (JVM).
Developer: Oracle CorporationVisit: http://netbeans.org
The End
http://twitter.com/rasansmn