1
Graphical User Interface(GUI)
Mehdi Einali
Advanced Programming in Java
2
AgendaIntro to Graphical User Interface (GUI)GUI PatternsGUI ComponentsEvent HandlersInner ClassesAnonymous Inner Classes
3
Intro to Gui
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”
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, …
6
7
Gui Graphics
8
combination
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
10
Java FXJava + Flash + Flex = Java FX
Cross Platform Rich Internet ApplicationMulti devices
Use Scene Builder which generate FXML
Compete with HTML5 on adoption!!
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
12
Gui patterns
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.
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
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
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)
17
observer
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.
19
observer
20
code
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
22
Consequences
Loose coupling between subject and observer, enhancing reuse
Support for broadcast communication
Notification can lead to further updates, causing a cascade effect
23
Swing listenersActionListenerAdjustmentListenerFocusListenerItemListenerKeyListenerMouseListener
MouseEventListenerMouseMotionListener
TreeExpansionListenerTextListenerWindowListenerand on and on…
24
Composite pattern
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.
26
Class diagram
27
use
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
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
30
layouts
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.
32
Class diagram
33
use
34
applicabilityMany classes differ in only their behavior
Client needs different variants of an algorithm
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
36
Other pattern in guiCommandMVC(Model View Controller)DecoratorFactory. . .
37
Gui Components
38
JOptionPaneJOptionPane class has simple static methods
for input and outputUsing Dialog boxes
JOptionPane.showInputDialogReturns a String
JOptionPane.showMessageDialogShows a dialog box
39
JOptionPane SampleString name = JOptionPane.showInputDialog("Enter your name:");
JOptionPane.showMessageDialog(null, "Salam "+name +"!");
40
Modal DialogJOptionPane dialogs are called modal dialogsWhile the dialog is on the screen…the user cannot interact with the rest of the application
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
42
JFrame ExampleJFrame frame = new JFrame();frame.setSize(300, 150);frame.setVisible(true);frame.setLayout(new FlowLayout());frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
43
Swing GUI ComponentsJButtonJLabelJTextFieldJComboBoxJRadioButtonJMenu…
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);
45
Other GUI ComponentsJTextField textbox = new JTextField(10);frame.add(textbox);
JComboBox combo = new JComboBox(new String[]{"Red", "Blue", "Green"});frame.add(combo);
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
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, …
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
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
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
51
Extending JFrameYou can also extend JFrame to create new frames…
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);
}}
53
Event handling
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
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
56
57
listeners
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!!!”);
}}
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
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()); } }}
61
Inner class
62
Class Typesclass FriendlyClass{
}public class OuterClass {private int value;
public class Inner{public void f(){
…}
}}
Friendly Class
Public class
Inner Class
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
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
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?
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();
}}
67
Inner Class SpecifiersstaticfinalAccess Specifiers
publicprivateFriendly (no specifier)protected
68
Anonymous Inner ClassAn inner classWith no nameCreated onceUsed onceNo access to this class from any other placeOnce created and used
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);
}}
70
Anonymous Inner class
71
Anonymous Inner ClassUsually implements an interfaceOr extends another classAnd Overrides some special methodMain Application : Event Handlers
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); }}
73
Further on GUIjavawJava Web Applications
Web Interface
SWTJava Look and Feels
Android Programming!!
74
end
Recommended