Post on 23-Dec-2015
Graphical User Interface Programming
Graphical User Interface Programming
Dr. Susan McKeever (not me)
Email: richard.lawlor@dit.ie
www.comp.dit.e/rlawlor
UI Programming
• At the end of the course you will be able to:– Develop GUI applications– Use standard UI components– Develop custom UI components
– And… Program in Java– And.. Be a better programmer
Admin
• Tutorial/Lecture/Lab– Lecture
• Provide new material• Usually new Lab exercises
– Lab• Work on latest Lab Sheet• Lab content will be a week behind the lecture..
– Tutorial • Discuss issues from last Lab Sheet• Review Broken Code/error messages
Course..
• Topics– Java Language Basics
• Hello World• Operators/Reference
Types• OO Basics• Packages• Abstractions• Exceptions
• Connecting to Databases JDBC
• “Good” programming practices
– GUIs (Java Swing)• Layout Managers• Event Handing• Graphics• Applets• GUI Design• Class structures and Model
View Controller (MVC)
Resources…
• Resources– Web, web, web, web, web, web,………………– JAVA API http://download.oracle.com/javase/6/docs/api/– Textbook:
UI Programming: Paul Fischer, An Intro to GUIs with Java SwingGeneral Reference: Java in a Nutshell, O’Reilly
Java Swing, O’Reilly 2nd Ed.
• Webcourses – www.comp.dit.ie/smckeever– CHECK YOU CAN ACCESS.. IF NOT EMAIL ME– Lecture notes– Lab Assignments & eventually Solutions– Assignments (Details and Submission)– Links to Useful References– Past Exam Papers.. Just 1 set..
Important
• Lecture notes are my guide to structuring lectures
• They do not contain all material covered
• Will do plenty of work/examples etc on the board
Java Editions
Java2 Standard Edition
(J2SE™)
Java2 Enterprise Edition
(J2EE™)
Java2 Micro Edition
(J2ME™)
Java 2 Platform
Standard desktop &workstation applications; applets
Heavy duty serverSystems – mediumto large companies
Small & memory constrained devices
Key Benefits of Java
• Java is “write once, run anywhere”– architecture neutral– portable across different platforms– Due to Java Virtual Machine (JVM)
• Security features– highly configurable security levels prevent
any piece of Java code doing harm to the host system
Key Benefits of Java
• Network-centric platform– easy to work with resources across a
network and to create network based applications
• Object Oriented– an interacting collection of independent
software components– dynamic extensible programs
Key Benefits of Java• Internationalisation
– uses 16 bit Unicode characters that represents the phonetic and ideographic character sets of the entire world
• Performance– although an interpreted language Java
programs run almost as fast as native C, C++ programs
• Simple and easy to develop– powerful & well designed set of APIs– http://download.oracle.com/javase/6/docs/
api/
JVM
class myCode {…………
}
myCode.java
Compiled by Java compiler
Application runs
Application runs
Interpreted by JVM
Source Code
1001100101001……
myCode.class
Bytecode
JVM
• JVM provides the run time environment for the bytecode (Java Runtime Environment JRE)
– executes the bytecode and causes native machine code instructions to execute on the CPU that the JVM is on
each target platform needs an implementation of the JVM
The Simplest Java Program
public class HelloWorld{
// no fields
// main methodpublic static void main (String []
args){
System.out.println("Hello World..");
}}
Basic Program structure
• Basic class definition - remember from OO programming last year?
class className {
// field declarations…// method declarations…
}
The Simplest Java Program
public class HelloWorld{
// no fields
// main methodpublic static void main (String []
args){
System.out.println("Hello World..");
}}To run a java program, you need a special methods called the main method to tell the program where to start executing
Simple Java Program
public class HelloWorld{
// no fields
// main methodpublic static void main (String []
args){
System.out.println("Hello World..");
}}
command line args
accessible to all classes(info hiding)
indicates class method
invoking a member
returns nothing
Not much point in creating an object out of this class.. It doesn’t describe anything.. It just “runs”
Objects
• An object includes state (fields) and behaviour (methods)
• A class object is the blueprint for the instance objects
• All code must be included in a class– no inline functions like C++
An Example Class
• Want to create a class that represents a student.
• Want to store a “name” for the student.
• How?
• Want to the class to have a way to print out the student name
• How?
An Example Class
public class Student {
// member fieldsprivate String name;
// constructorpublic Student(String name) {
this.name=name;}
// methods
public void printDetails(){
System.out.println("\nName: “ + name);}
}
An Example Class
public class Student {
// member fieldsprivate String name;
// constructorpublic Student(String name) {
this.name=name;}
// methods
public void printDetails(){
System.out.println("\nName: “ + name);}
}
a business
class
String concatenati
on
predefined Java class
no return type
reference to the object
itself
accessibility
Instantiation (i.e. creating objects out of a class)
• Class definition used to create a “class object” at runtime
• E.g. created a Student class.. Now want to create a “real” student object
• To instantiate “instance objects” use new operator
ClassName myInstance = new ClassName();
where ClassName() is a constructor
Note: no need to allocate the memory for the object like in C++
Using a Class in a Program
public class myProg {
public static void main(String args []){
// instantiate a Student object Student student1= new Student("Joe Bloggs");
Student student2= new Student(“Liz mckeever");
// invoke printDetails method student1.printDetails();
student2.printDetails();
}}
the program control class:
Contains “main”
source file called
myProg.java
Using the JDK
• Each class is stored in a source file “xxx.java”
• The name of source file should be the same as the name of class
public class myCode {…………
}
myCode.java
Source File
Compiling your source code
• Compile each class source file into bytecode (class files)
• In DOS To compile a java source file
javac myCode.java
• This creates a classfile called myCode.class
BUT.. This year we’re going to use Eclipse
1001101001110101011…………
myCode.class
Class File
Eclipse
An Integrated Development Environment (IDE)
Originally created by IBM (2001)
Open source community, free
Widely widely used in industry
Increases coding efficiency Spots compile errors as you type Allows quick fixes Helps file organisations/packages Imports are easy Demo..
To run your program
• All so easy in Eclipse..
–Click the “RUN” command in Eclipse – full instructions at the lab
Using a Control Class
// This is in a file call myControlClass.java
public class myControlClass {
public static void main(String args []){
// instantiate a Student object
new StudentPrinter();
}
}
Using a Control Class
// This is in a file call StudentPrinter.java
public class StudentPrinter {
// Constructor - instantiate a Student object
public StudentPrinter() {
Student student1= new Student("Joe Bloggs");
Student student2= new Student(“Liz mckeeve");
// invoke printDetails method
student1.printDetails();
student2.printDetails();
}
}
Using a Control Class
// This is in a file call Student.java
public class Student {// member fieldsprivate String name;
// constructor
public Student(String name){
this.name=name;}
// methods
public void printDetails(){
System.out.println("\nName: " + name);
}
}
General points to note..
• 80% of the cost of software is on maintaining code– Typically not the original developer
• “You cannot be good at s/w development if you don’t make it as easy as possible for someone else to maintain your code”
• Dr. Susan McKeever Sept 2012
Common sense
• Comment your code– Header at the top of your code– Every method explained
• Use meaningful names for variables, classes, objects...
• Use java conventions (see overleaf)
• Many more.. To be covered.
Use Conventions..
• Java is Case sensitive
• Use the conventions – Classes should be nouns, capitalised first
letter e.g.
Student, ImagePixel– Variables mixed case starting with lower.
E.g. acctBalance, line– Constant are all upper case e.g.
COLOR_RED– Methods are verbs, mixed case starting
with lower e.g. getBalance()
Primitive data types
• Using a variable in java.. You must declare what type of data can contain..– int, char etc..
• A primitive type is predefined by the language and is named by a reserved keyword.... 8 of them in java
Primitive data types
• char (16 bits) a Unicode character
• byte (8 bits)
• int (32 bits) a signed integer
• short (16 bits) a short integer
• long (64 bits) a long integer
Primitive data types
• float (32 bits) a real number
• double (64 bits) a large real number
• boolean (8 bits) – values are true or false (keywords)– Used with control statements e.g. while, do
, if – e.g. while (fileEmpty)
Operators
• Additive+ -
• Multiplicative* / %
• Equality (tests)== !=
• Assignment operators= += -= *= /= %=
Operators
• Relational operators< <= > >=
• Increment operators (postfix and prefix)++ --
• Conditional operator (short cut for if/else
?: e.g. max = (a > b) ? a : b;• String concatenation
+
Control Statements
• Similar to C/C++ syntax:– if statement
if (x != n){ …}else if {
… }else {
… }
– for statement for (int i=0; i<max; i++){
… };
Control Statements
– switch statement switch (n){ case 1:
… break;case 2: case 3:
… break;default: break;
};
Reference Types
• Classes and arrays are composite types – no standard size– contain other elements
• Manipulated “by reference’’ to the object or array
• Primitive data types manipulated “by value”
Reference vs Primitive Types
• A reference is a value that refers to the object or array
• A primitive datatype holds the value directly
• Difference to primitive types effects the way values are copied and compared
Setting Object A = Object B only sets the reference and does not set the contents
Comparing Object A and Object B, A will not be equal to B even if they have the same contents
References in Java
• Note: – Java does not support the & address-of or
-> and * de-reference operators of C and C++
– the . operator in Java is more like the -> operator of C++
– references in Java cannot be manipulated (e.g. incremented or decremented)
null
• null – is a special value indicating a reference to
nothing– can be assigned to a variable of any
reference type
Arrays in Java
• Array declaration – set the (1) size or (2) the values:
(1)type arrayId[] = new type[limit]; (2)type arrayId[] = new type[] {values};
• Multi dimensional array:
type arrayId[][] =new type[rowlimit][colLimit]
• Examples:int frequencies[]= new int[]{20,40,60};
String countryCode[]= new String[176]; double table[]=new double[4][5];
Arrays in Java
• Arrays can be formed from any data type or class
• Arrays are indexed from 0.• Arrays are fixed size but the size can be
allocated at run time:e.g. int array1[]; // declare array… …int size=n; // get array size,
array1 = new int [size]; // allocate array
• Assigning one array to another array copies the reference and does not copy full array.
Arrays in Java
• Accessing an array element that does not exist will result in an error
• The length of an array can be accessed using a read-only property called length that is associated with every array.
e.g. for (i=0; i<frequencies.length; i++)…
• Arrays can be passed as parameters to methods
e.g. main (String [] args)
Class & Array Interaction
• There are 3 ways that classes and arrays are used together
(1) An array of a class of objects:Student students[] =new Student[8];
(2) A class containing an array and methods that act on it
(3) A class containing methods that operate on array parameters
Class & Array Interaction (2)
A class containing an array and methods that act on it
class IntArray {private int arrayOfInt[];
IntArray(int size){ //constructor arrayOfInt=new int [size];}
int get(int index){ // get value at index return arrayOfInt[index];}
void set (int index, int value){ //set value arrayOfInt[index]=value;}
public String toString(){ // print out array String s =””; for (int i=0; i<arrayOfInt.length;i++) s += “ “+arrayOfInt[i]; return s;}
}
Class & Array Interaction (3)
A class containing methods that operate on array parameters
class ArrayUtilities {
static int max( int arrayA [] ) { // finds the max element of
arrayA // and returns it ...
return arrayA[i];}
static void sort (int [] arrayA) { //sorts the elements of arrayA
... } }
Array passed into to the
“sort” method as a parameter