Advanced Programming in Java Graphical User InterfaceGUI Mehdi

  • Slides: 80
Download presentation
Advanced Programming in Java Graphical User Interface(GUI) Mehdi Einali 1

Advanced Programming in Java Graphical User Interface(GUI) Mehdi Einali 1

Agenda Intro to Graphical User Interface (GUI) GUI Patterns GUI Components Event Handlers Inner

Agenda Intro to Graphical User Interface (GUI) GUI Patterns GUI Components Event Handlers Inner Classes Anonymous Inner Classes 2

Intro to Gui 3

Intro to Gui 3

Graphical User Interface GUI presents a mechanism for interacting with application. a user-friendly mechanism

Graphical User Interface GUI presents a mechanism for interacting with application. a user-friendly mechanism What are other mechanisms? Console Applications File Web Applications … GUI is pronounced “GOO-ee” 4

GUI Components GUIs are built from GUI components sometimes called controls or widgets widget:

GUI Components GUIs are built from GUI components sometimes called controls or widgets widget: short for window gadgets GUI component: an object with which the user interacts via the mouse or the keyboard Example? Button, Textbox, Menu, … 5

6

6

Gui Graphics 7

Gui Graphics 7

combination 8

combination 8

Swing AWT was the early way for GUI in java Abstract Window Toolkit Java.

Swing AWT was the early way for GUI in java Abstract Window Toolkit Java. awt package An AWT component’s behavior may be different between platforms. Swing is a newer approach In this presentation we review Swing GUI components javax. swing package 9

Java FX Java + Flash + Flex = Java FX Cross Platform Rich Internet

Java FX Java + Flash + Flex = Java FX Cross Platform Rich Internet Application Multi devices Use Scene Builder which generate FXML Compete with HTML 5 on adoption!! 10

Setup phase How gui works Describe how the GUI window should look Use libraries

Setup phase How gui works Describe how the GUI window should look Use libraries for windows, widgets, and layout Embed specialized code for later use Customization (provided during setup) New widgets that display themselves in custom ways How to react to events Execution Framework gets events from OS • Mouse clicks, key presses, window becomes visible, etc. Framework triggers application code in response • The customization described above 11

Design patterns 12

Design patterns 12

patterns "Each pattern describes a problem which occurs over and over again in our

patterns "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice“ Christopher Alexander: a building architect in the 1970’s Alexander’s idea was to improve the quality of the buildings of the time by utilizing proven ‘patterns’ of good architectural design. 13

Pattern in architecture Context: Interior design/ Shop design/ Small shop Problem: customer feel inconvenience

Pattern in architecture Context: Interior design/ Shop design/ Small shop Problem: customer feel inconvenience and want to leave soon Solutions: Use mirrors to make room space look larger 14

Pattern in architecture Alexander’s work ‘discovered’ by Kent Beck and friends in the 1980’s

Pattern in architecture Alexander’s work ‘discovered’ by Kent Beck and friends in the 1980’s They applied Alexander’s ideas about constructing buildings to the building of software. In nutshell § § proven software practice piece of literature building block possible abstraction levels: language construct idiom design pattern architectural pattern 15

Gof pattern In 1994 Go. F published the Bible(Design Patterns) Type of the patterns

Gof pattern In 1994 Go. F published the Bible(Design Patterns) Type of the patterns § Creational Focuses on simplifying object creation and referencing (Singleton, Abstract Factory) § Structural Govern how objects and classes work together (Adapters, proxy) § Behavioral Focuses on messages sent between objects (State, Observer) 16

Why Patterns Are Important Experience is a good teacher, but a fool will learn

Why Patterns Are Important Experience is a good teacher, but a fool will learn from no other Technologies always are emerging and decrease Patterns and Paradigms are repeating 17

layering You can understand a single layer as a coherent whole without knowing much

layering You can understand a single layer as a coherent whole without knowing much about the other layers. You can substitute layers with alternative implementations of the same basic services You minimize dependencies between layers. Layers make good places for standardization Once you have a layer built, you can use it for many higherlevel services. 18

19

19

Singleton The singleton pattern is a design pattern that is used to restrict instantiation

Singleton The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. 20

21

21

Gui patterns 22

Gui patterns 22

observer 23

observer 23

observer Subset of the asynchronous publish/subscribe pattern An object, called the subject, maintains a

observer Subset of the asynchronous publish/subscribe pattern An object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. 24

observer 25

observer 25

code 26

code 26

Applicability When an abstraction has two aspects, one dependent on the other, and you

Applicability When an abstraction has two aspects, one dependent on the other, and you want to reuse each When change to one object requires changing others, and you don’t know how many objects need to be changed When an object should be able to notify others without knowing who they are 27

Consequences Loose coupling between subject and observer, enhancing reuse Support for broadcast communication Notification

Consequences Loose coupling between subject and observer, enhancing reuse Support for broadcast communication Notification can lead to further updates, causing a cascade effect 28

Swing listeners Action. Listener Adjustment. Listener Focus. Listener Item. Listener Key. Listener Mouse. Event.

Swing listeners Action. Listener Adjustment. Listener Focus. Listener Item. Listener Key. Listener Mouse. Event. Listener Mouse. Motion. Listener Tree. Expansion. Listener Text. Listener Window. Listener and on… 29

Composite pattern 30

Composite pattern 30

Composite The Composite design pattern allows you to treat a collection of objects as

Composite The Composite design pattern allows you to treat a collection of objects as if they were one thing. In this way you can reduce the complexity of the code required if you were going to handle collections as special cases. 31

Class diagram 32

Class diagram 32

use 33

use 33

Applicability You want to represent part/whole hierarchies of objects You want to be able

Applicability You want to represent part/whole hierarchies of objects You want to be able to ignore the difference between compositions of objects and individual objects 34

Consequences Makes the client simple, since it can treat objects and composites uniformly Makes

Consequences Makes the client simple, since it can treat objects and composites uniformly Makes it easy to add new kinds of components Can make the design overly general Operations may not make sense on every class Composites may contain only certain components 35

layouts 36

layouts 36

strategy The Strategy pattern allows you to replace algorithms on the fly. To implement

strategy The Strategy pattern allows you to replace algorithms on the fly. To implement the solution, you represent each algorithm as a Strategy class. The application then delegates to the current Strategy class to execute the strategy-specific algorithm. 37

Class diagram 38

Class diagram 38

use 39

use 39

applicability Many classes differ in only their behavior Client needs different variants of an

applicability Many classes differ in only their behavior Client needs different variants of an algorithm 40

Consequences Code is more extensible with new strategies Compare to conditionals Separates algorithm from

Consequences Code is more extensible with new strategies Compare to conditionals Separates algorithm from context each can vary independently Adds objects and dynamism code harder to understand Common strategy interface may not be needed for all strategy implementations- may be extra overhead 41

Other pattern in gui Command MVC(Model View Controller) Decorator Factory. . . 42

Other pattern in gui Command MVC(Model View Controller) Decorator Factory. . . 42

Gui Components 43

Gui Components 43

JOption. Pane class has simple static methods for input and output Using Dialog boxes

JOption. Pane class has simple static methods for input and output Using Dialog boxes JOption. Pane. show. Input. Dialog Returns a String JOption. Pane. show. Message. Dialog Shows a dialog box 44

JOption. Pane Sample String name = JOption. Pane. show. Input. Dialog("Enter your name: ");

JOption. Pane Sample String name = JOption. Pane. show. Input. Dialog("Enter your name: "); JOption. Pane. show. Message. Dialog(null, "Salam "+name +"!"); 45

Modal Dialog JOption. Pane dialogs are called modal dialogs While the dialog is on

Modal Dialog JOption. Pane dialogs are called modal dialogs While the dialog is on the screen… the user cannot interact with the rest of the application 46

JFrame We create a window containing Swing GUI components This window object is usually

JFrame We create a window containing Swing GUI components This window object is usually instance of JFrame or a subclass of JFrame provides the basic attributes and behaviors of a window a title bar at the top minimize and maximize buttons close button 47

JFrame Example JFrame frame = new JFrame(); frame. set. Size(300, 150); frame. set. Visible(true);

JFrame Example JFrame frame = new JFrame(); frame. set. Size(300, 150); frame. set. Visible(true); frame. set. Layout(new Flow. Layout()); frame. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); 48

Swing GUI Components JButton JLabel JText. Field JCombo. Box JRadio. Button JMenu … 49

Swing GUI Components JButton JLabel JText. Field JCombo. Box JRadio. Button JMenu … 49

JLabel and JButton JLabel label = new JLabel("Salam"); label. set. Tool. Tip. Text("Tooltip 1");

JLabel and JButton JLabel label = new JLabel("Salam"); label. set. Tool. Tip. Text("Tooltip 1"); frame. add(label); JButton button = new JButton("Click!"); button. set. Tool. Tip. Text("salam : -)"); frame. add(button); 50

Other GUI Components JText. Field textbox = new JText. Field(10); frame. add(textbox); JCombo. Box

Other GUI Components JText. Field textbox = new JText. Field(10); frame. add(textbox); JCombo. Box combo = new JCombo. Box( new String[]{"Red", "Blue", "Green"}); frame. add(combo); 51

Layout Management You must attach each GUI component to a container such as a

Layout Management You must attach each GUI component to a container such as a JFrame. You typically must decide where to position each GUI component known as specifying the layout Java provides several layout managers They help you position components 52

Flow. Layout In Flow. Layout layout manager: components are placed on a container from

Flow. Layout In Flow. Layout layout manager: components are placed on a container from left to right in the order in which they’re added When no more components can fit on the current line continue on the next line Other layouts: Grid. Layout, Box. Layout, … 53

Layouts Three ways to arrange components in a GUI Layout managers Simple and Fast

Layouts Three ways to arrange components in a GUI Layout managers Simple and Fast Absolute positioning provides the greatest level of control GUI’s appearance. Visual programming in an IDE They generate codes They may use layout managers 54

Absolute Positioning Set Container’s layout to null Specify the absolute position of each GUI

Absolute Positioning Set Container’s layout to null Specify the absolute position of each GUI component with respect to the upper-left corner of the Container by using Component methods set. Size and set. Location or set. Bounds absolute positioning can be tedious unless you have a support by an IDE 55

IDE Support Many IDEs provide GUI design tools You can specify a component’s exact

IDE Support Many IDEs provide GUI design tools You can specify a component’s exact size and location in a visual manner by using the mouse simplifies creating GUIs Each IDE generates this code differently You should know the underlying codes Eclipse/Inteli. J Plugin 56

Extending JFrame You can also extend JFrame to create new frames… 57

Extending JFrame You can also extend JFrame to create new frames… 57

public class My. Frame extends JFrame{ JLabel label; JButton button; JText. Field textbox; JCombo.

public class My. Frame extends JFrame{ JLabel label; JButton button; JText. Field textbox; JCombo. Box combo; public My. Frame(){ super("Frame Title"); label = new JLabel("Salam"); label. set. Tool. Tip. Text("Label Tooltip"); add(label); button = new JButton("Click!"); button. set. Tool. Tip. Text("salam : -)"); add(button); textbox = new JText. Field(10); add(textbox); combo = new JCombo. Box( new String[]{"Red", "Blue", "Green"}); add(combo); } } 58

Event handling 59

Event handling 59

Event Handling GUIs are event driven User interaction => events An Event drives the

Event Handling GUIs are event driven User interaction => events An Event drives the program to perform a task Some events: clicking a button typing in a text field selecting an item from a menu closing a window moving the mouse 60

Event Handling (2) event handler : The code that performs a task in response

Event Handling (2) event handler : The code that performs a task in response to an event handling : The overall process of responding to events 61

62

62

listeners 63

listeners 63

Event Handlers button = new JButton("Click!"); Action. Listener al = new Click. Listener(); button.

Event Handlers button = new JButton("Click!"); Action. Listener al = new Click. Listener(); button. add. Action. Listener(al); public class Click. Listener implements Action. Listener { public void action. Performed(Action. Event e) { JOption. Pane. show. Message. Dialog(null, “Salam!!!”); } } 64

Better Event Handlers I want to show a message-box According to the value of

Better Event Handlers I want to show a message-box According to the value of a component For example a text-field or a combo-box How can I do that? Inner Classes 65

public class My. Frame extends JFrame{ JButton button; JText. Field textbox; public My. Frame(){

public class My. Frame extends JFrame{ JButton button; JText. Field textbox; public My. Frame(){ button = new JButton("Click!"); button. add. Action. Listener(new Click. Listener()); add(button); textbox = new JText. Field(10); add(textbox); } class Click. Listener implements Action. Listener { public void action. Performed(Action. Event e) { JOption. Pane. show. Message. Dialog(null, textbox. get. Text()); } } } 66

Inner class 67

Inner class 67

Class Types class Friendly. Class{ Friendly Class } public class Outer. Class { private

Class Types class Friendly. Class{ Friendly Class } public class Outer. Class { private int value; public class Inner{ public void f(){ … } } } 68 Public class Inner Class

Inner Classes Declared in another class Instantiated using a reference object of outer class

Inner Classes Declared in another class Instantiated using a reference object of outer class Has access to this object The inner class can be static No reference object of outer class is needed No access to outer class is provided 69

public class Outer. Class { private int value = 2; class Inner{ public void

public class Outer. Class { private int value = 2; class Inner{ public void inner. Method(){ Outer. Class. this. value = 5; } } public void outer. Method(){ Outer. Class. this is implicitly Inner inner = new Inner(); saved in inner object inner. Method(); } public static void main(String[] args) { Outer. Class outer = new Outer. Class(); System. out. println(outer. value); outer. Method(); System. out. println(outer. value); } } 70

public class Outer. Class { private int value = 2; class Inner{ public void

public class Outer. Class { private int value = 2; class Inner{ public void f(){ Outer. Class. this. value = 5; } } public static void main(String[] args) { Outer. Class outer = new Outer. Class(); Outer. Class. Inner inner = outer. new Inner(); System. out. println(outer. value); inner. f(); System. out. println(outer. value); } } 71 Why we need outer reference?

class Outer. Class { static class Inner{ public void f(){ System. out. println("f() invoked");

class Outer. Class { static class Inner{ public void f(){ System. out. println("f() invoked"); } } } public class Main. Class { public static void main(String[] args) { Outer. Class. Inner in = new Outer. Class. Inner(); in. f(); } } 72

Inner Class Specifiers static final Access Specifiers public private Friendly (no specifier) protected 73

Inner Class Specifiers static final Access Specifiers public private Friendly (no specifier) protected 73

Anonymous Inner Class An inner class With no name Created once Used once No

Anonymous Inner Class An inner class With no name Created once Used once No access to this class from any other place Once created and used 74

interface My. Interface{ void inner. Method(); } public class Outer. Class { private int

interface My. Interface{ void inner. Method(); } public class Outer. Class { private int value = 2; public void outer. Method(){ My. Interface inner = new My. Interface() { public void inner. Method() { Outer. Class. this. value = 5; } }; inner. Method(); } public static void main(String[] args) { Outer. Class outer = new Outer. Class(); System. out. println(outer. value); outer. Method(); System. out. println(outer. value); } } 75

Anonymous Inner class 76

Anonymous Inner class 76

Anonymous Inner Class Usually implements an interface Or extends another class And Overrides some

Anonymous Inner Class Usually implements an interface Or extends another class And Overrides some special method Main Application : Event Handlers 77

public class My. Frame extends JFrame{ JButton button; JText. Field textbox; public My. Frame(){

public class My. Frame extends JFrame{ JButton button; JText. Field textbox; public My. Frame(){ button = new JButton("Click!"); button. add. Action. Listener(new Action. Listener() { public void action. Performed(Action. Event e) { JOption. Pane. show. Message. Dialog(null, textbox. get. Text()); } }); add(button); textbox = new JText. Field(10); add(textbox); } } 78

Further on GUI javaw Java Web Applications Web Interface SWT Java Look and Feels

Further on GUI javaw Java Web Applications Web Interface SWT Java Look and Feels Android Programming!! 79

end 80

end 80