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

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

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

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

1

Graphical User Interface(GUI)

Mehdi Einali

Advanced Programming in Java

Page 2: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

2

AgendaIntro to Graphical User Interface (GUI)GUI PatternsGUI ComponentsEvent HandlersInner ClassesAnonymous Inner Classes

Page 3: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

3

Intro to Gui

Page 4: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

4

Graphical User InterfaceGUI presents a mechanism for interacting with application.

a user-friendly mechanism

What are other mechanisms?Console ApplicationsFileWeb Applications…

GUI is pronounced “GOO-ee”

Page 5: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

5

GUI ComponentsGUIs are built from GUI components

sometimes called controls or widgetswidget: short for window gadgets

GUI component: an object with which the user interacts via the mouse or the keyboardExample?

Button, Textbox, Menu, …

Page 6: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

6

Page 7: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

7

Gui Graphics

Page 8: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

8

combination

Page 9: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

9

SwingAWT was the early way for GUI in java

Abstract Window ToolkitJava.awt package

An AWT component’s behavior may be different between platforms.

Swing is a newer approachIn this presentation we review Swing GUI components javax.swing package

Page 10: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

10

Java FXJava + Flash + Flex = Java FX

Cross Platform Rich Internet ApplicationMulti devices

Use Scene Builder which generate FXML

Compete with HTML5 on adoption!!

Page 11: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

11

How gui worksSetup phase

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 waysHow to react to events

ExecutionFramework gets events from OS• Mouse clicks, key presses, window becomesvisible, etc.Framework triggers application code inresponse• The customization described above

Page 12: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

12

Gui patterns

Page 13: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

13

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.

Page 14: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

14

Pattern in architectureContext: Interior design/ Shop design/ Small shop

Problem: customer feel inconvenience and want to leave soon

Solutions: Use mirrors to make room space look larger

Page 15: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

15

Pattern in architectureAlexander’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 constructidiomdesign patternarchitectural pattern

Page 16: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

16

Gof patternIn 1994 GoF published the Bible(Design Patterns)

Type of the patterns Creational

Focuses on simplifying object creation and referencing(Singleton, Abstract Factory)

StructuralGovern how objects and classes work together(Adapters, proxy)

BehavioralFocuses on messages sent between objects(State, Observer)

Page 17: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

17

observer

Page 18: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

18

observerSubset of the asynchronous publish/subscribe patternAn 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.

Page 19: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

19

observer

Page 20: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

20

code

Page 21: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

21

ApplicabilityWhen 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

Page 22: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

22

Consequences

Loose coupling between subject and observer, enhancing reuse

Support for broadcast communication

Notification can lead to further updates, causing a cascade effect

Page 23: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

23

Swing listenersActionListenerAdjustmentListenerFocusListenerItemListenerKeyListenerMouseListener

MouseEventListenerMouseMotionListener

TreeExpansionListenerTextListenerWindowListenerand on and on…

Page 24: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

24

Composite pattern

Page 25: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

25

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

Page 26: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

26

Class diagram

Page 27: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

27

use

Page 28: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

28

Applicability You want to represent part/whole hierarchies of objectsYou want to be able to ignorethe difference between compositions of objects and individual objects

Page 29: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

29

ConsequencesMakes the client simple, since it can treat objects and composites uniformlyMakes it easy to add new kinds of componentsCan make the design overly generalOperations may not make sense on every classComposites may contain only certain components

Page 30: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

30

layouts

Page 31: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

31

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

Page 32: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

32

Class diagram

Page 33: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

33

use

Page 34: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

34

applicabilityMany classes differ in only their behavior

Client needs different variants of an algorithm

Page 35: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

35

ConsequencesCode is more extensible with new strategies

Compare to conditionals

Separates algorithm from context each can vary independently

Adds objects and dynamismcode harder to understand

Common strategy interfacemay not be needed for all strategy implementations- may be extra overhead

Page 36: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

36

Other pattern in guiCommandMVC(Model View Controller)DecoratorFactory. . .

Page 37: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

37

Gui Components

Page 38: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

38

JOptionPaneJOptionPane class has simple static methods

for input and outputUsing Dialog boxes

JOptionPane.showInputDialogReturns a String

JOptionPane.showMessageDialogShows a dialog box

Page 39: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

39

JOptionPane SampleString name = JOptionPane.showInputDialog("Enter your name:");

JOptionPane.showMessageDialog(null, "Salam "+name +"!");

Page 40: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

40

Modal DialogJOptionPane dialogs are called modal dialogsWhile the dialog is on the screen…the user cannot interact with the rest of the application

Page 41: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

41

JFrameWe create a window containing Swing GUI components This window object is usually instance of JFrame or a subclass of JFrameJFrame provides the basic attributes and behaviors of a window

a title bar at the topminimize and maximize buttons close button

Page 42: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

42

JFrame ExampleJFrame frame = new JFrame();frame.setSize(300, 150);frame.setVisible(true);frame.setLayout(new FlowLayout());frame.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);

Page 43: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

43

Swing GUI ComponentsJButtonJLabelJTextFieldJComboBoxJRadioButtonJMenu…

Page 44: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

44

JLabel and JButtonJLabel label = new JLabel("Salam");label.setToolTipText("Tooltip1");frame.add(label);

JButton button = new JButton("Click!"); button.setToolTipText("salam :-)");frame.add(button);

Page 45: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

45

Other GUI ComponentsJTextField textbox = new JTextField(10);frame.add(textbox);

JComboBox combo = new JComboBox(new String[]{"Red", "Blue", "Green"});frame.add(combo);

Page 46: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

46

Layout ManagementYou 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

Page 47: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

47

FlowLayoutIn FlowLayout 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:GridLayout, BoxLayout, …

Page 48: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

48

LayoutsThree ways to arrange components in a GUILayout managers

Simple and Fast

Absolute positioningprovides the greatest level of control GUI’s appearance.

Visual programming in an IDEThey generate codesThey may use layout managers

Page 49: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

49

Absolute PositioningSet Container’s layout to nullSpecify the absolute position of each GUI component with respect to the upper-left corner of the Containerby using Component methods

setSize and setLocation or setBounds

absolute positioning can be tediousunless you have a support by an IDE

Page 50: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

50

IDE SupportMany 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/InteliJ Plugin

Page 51: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

51

Extending JFrameYou can also extend JFrame to create new frames…

Page 52: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

52

public class MyFrame extends JFrame{JLabel label;JButton button;JTextField textbox;JComboBox combo;public MyFrame(){

super("Frame Title");label = new JLabel("Salam");label.setToolTipText("Label Tooltip");add(label);button = new JButton("Click!"); button.setToolTipText("salam :-)");add(button);textbox = new JTextField(10);add(textbox);combo = new JComboBox(new String[]{"Red", "Blue", "Green"});add(combo);

}}

Page 53: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

53

Event handling

Page 54: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

54

Event HandlingGUIs are event drivenUser interaction => eventsAn Event drives the program to perform a taskSome events:

clicking a buttontyping in a text fieldselecting an item from a menuclosing a window moving the mouse

Page 55: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

55

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

event handling :The overall process of responding to events

Page 56: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

56

Page 57: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

57

listeners

Page 58: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

58

Event Handlersbutton = new JButton("Click!"); ActionListener al =

new ClickListener();button.addActionListener(al);

public class ClickListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(null, “Salam!!!”);

}}

Page 59: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

59

Better Event HandlersI want to show a message-boxAccording to the value of a componentFor example a text-field or a combo-box

How can I do that?Inner Classes

Page 60: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

60

public class MyFrame extends JFrame{

JButton button; JTextField textbox; public MyFrame(){ button = new JButton("Click!"); button.addActionListener(new ClickListener()); add(button); textbox = new JTextField(10); add(textbox); }class ClickListener implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, textbox.getText()); } }}

Page 61: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

61

Inner class

Page 62: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

62

Class Typesclass FriendlyClass{

}public class OuterClass {private int value;

public class Inner{public void f(){

…}

}}

Friendly Class

Public class

Inner Class

Page 63: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

63

Inner ClassesDeclared in another classInstantiated using a reference object of outer classHas access to this objectThe inner class can be static

No reference object of outer class is neededNo access to outer class is provided

Page 64: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

64

public class OuterClass {private int value = 2;

class Inner{public void innerMethod(){

OuterClass.this.value = 5;}

}

public void outerMethod(){Inner inner = new Inner();inner.innerMethod();

}public static void main(String[] args) {

OuterClass outer = new OuterClass();System.out.println(outer.value);outer.outerMethod();System.out.println(outer.value);

}}

OuterClass.this is implicitly saved in inner object

Page 65: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

65

public class OuterClass {private int value = 2;

class Inner{public void f(){

OuterClass.this.value = 5;}

}

public static void main(String[] args) {

OuterClass outer = new OuterClass();

OuterClass.Inner inner = outer.new Inner();

System.out.println(outer.value);inner.f();System.out.println(outer.value);

}}

Why we need outer reference?

Page 66: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

66

class OuterClass {static class Inner{

public void f(){System.out.println("f() invoked");

}}

}

public class MainClass { public static void main(String[] args) {

OuterClass.Inner in = new OuterClass.Inner(); in.f();

}}

Page 67: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

67

Inner Class SpecifiersstaticfinalAccess Specifiers

publicprivateFriendly (no specifier)protected

Page 68: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

68

Anonymous Inner ClassAn inner classWith no nameCreated onceUsed onceNo access to this class from any other placeOnce created and used

Page 69: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

69

interface MyInterface{ void innerMethod();}

public class OuterClass {private int value = 2;public void outerMethod(){

MyInterface inner = new MyInterface() {public void innerMethod() {

OuterClass.this.value = 5;}

};inner.innerMethod();

}public static void main(String[] args) {

OuterClass outer = new OuterClass();System.out.println(outer.value);outer.outerMethod();System.out.println(outer.value);

}}

Page 70: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

70

Anonymous Inner class

Page 71: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

71

Anonymous Inner ClassUsually implements an interfaceOr extends another classAnd Overrides some special methodMain Application : Event Handlers

Page 72: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

72

public class MyFrame extends JFrame{ JButton button; JTextField textbox;

public MyFrame(){ button = new JButton("Click!");

button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, textbox.getText()); } });

add(button); textbox = new JTextField(10); add(textbox); }}

Page 73: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

73

Further on GUIjavawJava Web Applications

Web Interface

SWTJava Look and Feels

Android Programming!!

Page 74: Graphical User Interface(GUI) Mehdi Einali Advanced Programming in Java 1.

74

end