dise - windows based application development in java

100
Diploma in Software Engineering Module VI: Windows Based Application Development in Java Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.

Upload: rasan-samarasinghe

Post on 19-Feb-2017

21 views

Category:

Education


2 download

TRANSCRIPT

Page 1: DISE - Windows Based Application Development in Java

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.

Page 2: DISE - Windows Based Application Development in Java

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

Page 3: DISE - Windows Based Application Development in Java

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

Page 4: DISE - Windows Based Application Development in Java

Features of Java

Object Oriented Platform independent Simple Secure Portable Robust Multi-threaded Interpreted High Performance

Page 5: DISE - Windows Based Application Development in Java

What you can create by Java?

• Desktop (GUI) applications• Enterprise level applications• Web applications• Web services• Java Applets• Mobile applications

Page 6: DISE - Windows Based Application Development in Java

Start Java Programming

What you need to program in Java?

Java Development Kit (JDK)Microsoft Notepad or any other text editorCommand Prompt

Page 7: DISE - Windows Based Application Development in Java

Creating First Java Program

public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}

MyFirstApp.java

Page 8: DISE - Windows Based Application Development in Java

Java Virtual Machine (JVM)

Page 9: DISE - Windows Based Application Development in Java

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.

Page 10: DISE - Windows Based Application Development in Java

Basic Rules to Remember

Java is case sensitive…

Hello not equals to hello

Page 11: DISE - Windows Based Application Development in Java

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

Page 12: DISE - Windows Based Application Development in Java

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

Page 13: DISE - Windows Based Application Development in 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");}}

Page 14: DISE - Windows Based Application Development in Java

Basic Rules to Remember

Tokens must be separated by WhitespacesExcept ( ) ; { } . [ ] + - * / =

public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}

Page 15: DISE - Windows Based Application Development in Java

Keywords in Java

Page 16: DISE - Windows Based Application Development in Java

Comments in Java Programs

Comments for single line

// this is a single line comment

For multiline

/* this is a multilinecomment*/

Page 17: DISE - Windows Based Application Development in Java

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

Page 18: DISE - Windows Based Application Development in Java

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

Page 19: DISE - Windows Based Application Development in Java

Variable Declaration in Java

Variable declarationtype variable_list;

Variable declaration and initializationtype variable_name = value;

Page 20: DISE - Windows Based Application Development in Java

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'.

Page 21: DISE - Windows Based Application Development in Java

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

Page 22: DISE - Windows Based Application Development in Java

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

Page 23: DISE - Windows Based Application Development in Java

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

Page 24: DISE - Windows Based Application Development in Java

Logical Operators

Operator Name Example

&& AND (A && B) is False

|| OR (A || B) is True

! NOT !(A && B) is True

A = True, B = False

Page 25: DISE - Windows Based Application Development in Java

If Statement

if(Boolean_expression){ //Statements will execute if the Boolean

expression is true}

Page 26: DISE - Windows Based Application Development in Java

If Statement

Boolean Expression

Statements

True

False

Page 27: DISE - Windows Based Application Development in Java

If… Else Statement

if(Boolean_expression){ //Executes when the Boolean expression is

true}else{ //Executes when the Boolean expression is

false}

Page 28: DISE - Windows Based Application Development in Java

If… Else Statement

Boolean Expression

Statements

True

False

Statements

Page 29: DISE - Windows Based Application Development in Java

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.}

Page 30: DISE - Windows Based Application Development in Java

If… Else if… Else Statement

Boolean expression 1

False

Statements

Boolean expression 2

Boolean expression 3

Statements

Statements

False

False

Statements

True

True

True

Page 31: DISE - Windows Based Application Development in Java

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 }}

Page 32: DISE - Windows Based Application Development in Java

Nested If Statement

Boolean Expression 1

True

False

StatementsBoolean Expression 2

True

False

Page 33: DISE - Windows Based Application Development in Java

While Loop

while(Boolean_expression) { //Statements}

Page 34: DISE - Windows Based Application Development in Java

While Loop

Boolean Expression

Statements

True

False

Page 35: DISE - Windows Based Application Development in Java

Do While Loop

do { //Statements}while(Boolean_expression);

Page 36: DISE - Windows Based Application Development in Java

Do While Loop

Boolean Expression

Statements

True

False

Page 37: DISE - Windows Based Application Development in Java

For Loop

for(initialization; Boolean_expression; update) { //Statements}

Page 38: DISE - Windows Based Application Development in Java

For Loop

Boolean Expression

Statements

True

False

Update

Initialization

Page 39: DISE - Windows Based Application Development in Java

Nested Loop

Boolean Expression

True

False

Boolean Expression

Statements

True

False

Page 40: DISE - Windows Based Application Development in Java

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);}}

Page 41: DISE - Windows Based Application Development in Java

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

Page 42: DISE - Windows Based Application Development in Java

Building a Single Dimensional Array

// Creating an ArrayDataType[] ArrayName = new DataType[size];

// Assigning valuesArrayName[index] = value;ArrayName[index] = value;……..

Page 43: DISE - Windows Based Application Development in Java

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

Page 44: DISE - Windows Based Application Development in Java

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

Page 45: DISE - Windows Based Application Development in Java

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

Page 46: DISE - Windows Based Application Development in Java

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

Page 47: DISE - Windows Based Application Development in Java

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>”;

Page 48: DISE - Windows Based Application Development in Java

Useful Operations with Strings

• concat()• length()• charAt(<index>)• substring(int <begin index>, int <end index>)• trim()• toLowerCase() • toUpperCase()

Page 49: DISE - Windows Based Application Development in Java

Java Objects and Classes

Page 50: DISE - Windows Based Application Development in Java

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

Page 51: DISE - Windows Based Application Development in Java

Java Objects

Dog myPet = new Dog(); //creating an object //Assigning values to AttributesmyPet.name = “Scooby”; myPet.color = “Brown”;

//calling methodmyPet.bark();

Page 52: DISE - Windows Based Application Development in Java

Methods

Method is a group of statements to perform a specific task.

• Methods with Return Value• Methods without Return Value

Page 53: DISE - Windows Based Application Development in Java

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

Page 54: DISE - Windows Based Application Development in Java

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

Page 55: DISE - Windows Based Application Development in Java

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

Page 56: DISE - Windows Based Application Development in Java

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”);}

}

Page 57: DISE - Windows Based Application Development in Java

Variable Types

Variables in a Class can be categorize into three types

1. Local Variables2. Instance Variables3. Static/Class Variables

Page 58: DISE - Windows Based Application Development in Java

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”);}

}

Page 59: DISE - Windows Based Application Development in Java

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”);}

}

Page 60: DISE - Windows Based Application Development in Java

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.

Page 61: DISE - Windows Based Application Development in Java

Inheritance

class Vehicle{//attributes and methods}

class Car extends Vehicle{//attributes and methods}

class Van extends Vehicle{//attributes and methods}

Vehicle

Car Van

Page 62: DISE - Windows Based Application Development in Java

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”);}}

Page 63: DISE - Windows Based Application Development in Java

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”);}

}

Page 64: DISE - Windows Based Application Development in Java

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!”);}

}

Page 65: DISE - Windows Based Application Development in Java

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();

Page 66: DISE - Windows Based Application Development in Java

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>;

Page 67: DISE - Windows Based Application Development in Java

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

Page 68: DISE - Windows Based Application Development in Java

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

Page 69: DISE - Windows Based Application Development in Java

Encapsulationclass student{

private int age;

public int getAge(){return age;}

public void setAge(int n){age = n;}

}

Data

Input OutputMethod Method

Method

Page 70: DISE - Windows Based Application Development in Java

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

Page 71: DISE - Windows Based Application Development in Java

Exception Hierarchy

Throwable

Exception Error

IOException RuntimeException ThreadDeath

ArithmeticException NullPointerException ClassCastException

******

Page 72: DISE - Windows Based Application Development in Java

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.

Page 73: DISE - Windows Based Application Development in Java

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

Page 74: DISE - Windows Based Application Development in Java

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.

Page 75: DISE - Windows Based Application Development in Java

JDBC

A. What is JDBC?B. JDBC ArchitectureC. Creating JDBC ApplicationD. StatementsE. Statement Execute MethodsF. Types of Result SetsG. Result Set Methods

Page 76: DISE - Windows Based Application Development in Java

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

Page 77: DISE - Windows Based Application Development in Java

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.

Page 78: DISE - Windows Based Application Development in Java

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

Page 79: DISE - Windows Based Application Development in Java

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

Page 80: DISE - Windows Based Application Development in Java

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.

Page 81: DISE - Windows Based Application Development in Java

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”);

Page 82: DISE - Windows Based Application Development in Java

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);

Page 83: DISE - Windows Based Application Development in Java

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()

Page 84: DISE - Windows Based Application Development in Java

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

Page 85: DISE - Windows Based Application Development in Java

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

Page 86: DISE - Windows Based Application Development in Java

Swing Components Hierarchy

Page 87: DISE - Windows Based Application Development in Java

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!

Page 88: DISE - Windows Based Application Development in Java

Using Frame

JFrame f = new JFrame("GUI Application");f.setBounds(300,300,400,250);f.setVisible(true);

Page 89: DISE - Windows Based Application Development in Java

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

Page 90: DISE - Windows Based Application Development in Java

Using Button

JButton btnOK = new JButton("OK");btnOK.setBounds(140,80,100,25);f.getContentPane().add(btnOK);

Page 91: DISE - Windows Based Application Development in Java

Using Label

JLabel lblWelcome = new JLabel("Welcome");lblWelcome.setBounds(155,80,100,25);f.getContentPane().add(lblWelcome);

Page 92: DISE - Windows Based Application Development in Java

Using Text Field

JTextField txtInput = new JTextField();txtInput.setBounds(155,80,100,25);f.getContentPane().add(txtInput);

Page 93: DISE - Windows Based Application Development in Java

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);

Page 94: DISE - Windows Based Application Development in Java

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

Page 95: DISE - Windows Based Application Development in Java

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.

Page 96: DISE - Windows Based Application Development in Java

How Events Handling Work?

Page 97: DISE - Windows Based Application Development in Java

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);

Page 98: DISE - Windows Based Application Development in Java

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);

Page 99: DISE - Windows Based Application Development in Java

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

Page 100: DISE - Windows Based Application Development in Java

The End

http://twitter.com/rasansmn