SlideShare une entreprise Scribd logo
1  sur  28
INTRODUCTION TO
GRAPHICAL USER
INTERFACES (GUIS)
Lecture 10
CS2110 – Fall 2009
Announcements
2
 A3 will be posted shortly, please start early
 Prelim 1: Thursday October 14, Uris Hall G01
 We do NOT have any scheduled makeup exam
 People with conflicts can take the exam early.
 The NORMAL scheduled time is 7:30-9:00
 If you have a conflict, take it from 6:00-7:30
 Out of town conflicts: you’ll take it during one of these
two time periods, supervised by some trustworthy
person, who can receive exam/send it back
Interactive Programs
3
 “Classic” view of
computer programs:
transform inputs to
outputs, stop
 Event-driven programs:
interactive, long-
running
 Servers interact with clients
 Applications interact with user(s)
user user
program
input
events
output
events
input
output
GUI Motivation
Interacting with a
program
 Program-Driven = Proactive
 Statements execute in sequential,
predetermined order
 Typically use keyboard or file I/O,
but program determines when that
happens
 Usually sing le -thre ade d
 Event-Driven = Reactive
 Program waits for user input to
activate certain statements
 Typically uses a GUI (Graphical
User Interface)
 Often m ulti-thre ade d
 Design...Which to
pick?
 Program called by another
program?
 Program used at command
line?
 Program interacts often with
user?
 Program used in window
environment?
 How does Java do
GUIs?
4
Java Support for Building GUIs
Java Foundation
Classes
 Classes for building GUIs
 Major components
 awt and swing
 Pluggable look-and-feel support
 Accessibility API
 Java 2D API
 Drag-and-drop Support
 Internationalization
 Our main focus: Swing
 Building blocks of GUIs
 Windows & components
 User interactions
 Built upon the AWT (Abstract
Window Toolkit)
 Java event model
 Why Swing?
 Easier to understand than SWT
 Lonnie used SWT in A3 but you
don’t actually need to understand
the code he wrote
5
Swing versus SWT versus AWT
 AWT came first
 Swing builds on AWT
 Strives for total
portability
 Secretly seems to have
a grudge against
Windows
 Basic architecture is
pretty standard
 SWT is “new”
 Goal is best
performance
 Great fit with
Windows system
 Basic architecture is
pretty standard
6
 We use SWT in A3
Java Foundation Classes
7
Pluggable Look-and-Feel Support
 Controls look-and-feel for particular windowing environment
 E.g., Java, Windows, Mac
Accessibility API
 Supports assistive technologies such as screen readers and Braille
Java 2D
 Drawing
 Includes rectangles, lines, circles, images, ...
Drag-and-drop
 Support for drag and drop between Java application and a native
application
Internationalization
 Support for other languages
GUI Statics and GUI Dynamics
 Components
 buttons, labels, lists, sliders,
menus, ...
 Containers: components that
contain other components
 frames, panels, dialog
boxes, ...
 Layout managers: control
placement and sizing of
components
 Events
 button-press, mouse-click,
key-press, ...
 Listeners: an object that
responds to an event
 Helper classes
 Graphics, Color, Font,
FontMetrics, Dimension, ...
8
Statics: what’s drawn on the
screen
Dynamics: user interactions
Creating a Window in SWT
9
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
public class HelloWorld {
public static void main(String[] args) {
//create the window
Display display = new Display();
Shell shell = new Shell(display);
Label label = new Label(shell, SWT.NONE);
label.setText("Basic Test!");
label.pack();
shell.pack();
shell.open();
// quit Java after closing the window
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose ();
}
}
Creating a Window in Swing
10
import javax.swing.*;
public class Basic1 {
public static void main(String[] args) {
//create the window
JFrame f = new JFrame("Basic Test!");
//quit Java after closing the window
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(200, 200); //set size in pixels
f.setVisible(true); //show the window
}
}
Things to notice
 Code style is similar
 Both are really “customizing” a prebuilt framework
 You write little bits and pieces of software that
runs in the context of the preexisting structure
 SWT oriented towards somewhat finer control
 Swing aims for a sturdy design, but can be
harder to customize.
11
Creating a Window Using a Constructor
12
 import javax.swing.*;
 public class Basic2 extends JFrame {
 public static void main(String[] args) {
 new Basic2();
 }
 public Basic2() {
 setTitle("Basic Test2!"); //set the title
 //quit Java after closing the window
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 setSize(200, 200); //set size in pixels
 setVisible(true); //show the window
 }
 }
A More Extensive Example
13  import javax.swing.*;
 import java.awt.*;
 import java.awt.event.*;
 public class Intro extends JFrame {
 private int count = 0;
 private JButton myButton = new JButton("Push Me!");
 private JLabel label = new JLabel("Count: " + count);
 public Intro() {
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 setLayout(new FlowLayout(FlowLayout.LEFT)); //set layout manager
 add(myButton); //add components
 add(label);
 myButton.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent e) {
 count++;
 label.setText("Count: " + count);
 }
 });
 pack();
 setVisible(true);
 }
 public static void main(String[] args) {
 try {
 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
 } catch (Exception exc) {}
 new Intro();
 }
 }
GUI Statics
14
Determine which co m po ne nts you want
Choose a top-level co ntaine r in which to put
the components (JFrame is often a good
choice)
Choose a layo ut m anag e r to determine how
components are arranged
Place the components
Components = What You See
15
 Visual part of an interface
 Represents something with position and size
 Can be painte d on screen and can receive
events
 Buttons, labels, lists, sliders, menus, ...
 Some windows have hidden components that
become visible only when the user takes some
action
Component Examples
16
 import javax.swing.*;
 import java.awt.*;
 public class ComponentExamples extends JFrame {
 public ComponentExamples() {
 setLayout(new FlowLayout(FlowLayout.LEFT));
 add(new JButton("Button"));
 add(new JLabel("Label"));
 add(new JComboBox(new String[] { "A", "B", "C" }));
 add(new JCheckBox("JCheckBox"));
 add(new JSlider(0, 100));
 add(new JColorChooser());
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 pack();
 setVisible(true);
 }
 public static void main(String[] args) {
 try {
 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
 } catch (Exception exc) {}
 new ComponentExamples();
 }
 }
More Components
17
JFileChooser: allows choosing a file
JLabel: a simple text label
JTextArea: editable text
JTextField: editable text (one line)
JScrollBar: a scrollbar
JPopupMenu: a pop-up menu
JProgressBar: a progress bar
Lots more!
Layout
 Issue here concerns the way the components
are placed on the screen
 If you do it statically (and you can), the
resulting application can’t be resized easily
 So GUI builders offer a more dynamic option
18
Containers
19
A container is a component
that
 Can hold other components
 Has a layout manager
Heavyweight vs. lightweight
 A heavyweight component
interacts directly with the
host system
 JWindow, JFrame, and
JDialog are heavyweight
 Except for these top-level
containers, Swing
components are almost all
lightweight
 JPanel is lightweight
 There are three basic top-level
containers
 JWindow: top-level window with no
border
 JFrame: top-level window with border
and (optional) menu bar
 JDialog: used for dialog windows
 Another important container
 JPanel: used mostly to organize
objects within other containers
A Component Tree
20
JFrame
JPanel
JPanel JPanel
JPanel JPanel
JPanel JPanel
JComboBox (mi)
JComboBox (km)
JTextField (2000)
JSlider
JTextField (3226)
JSlider
JPanelJPanel
Layout Managers
21
 A layout manager controls
placement and sizing of
components in a container
 If you do not specify a layout
manager, the container will use a
default:
 JPanel default = FlowLayout
 JFrame default = BorderLayout
 Five common layout managers:
BorderLayout, BoxLayout,
FlowLayout, GridBagLayout,
GridLayout
 General syntax
container.setLayout(new LayoutMan());
 Examples:
JPanel p1 =
new JPanel(new BorderLayout());
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
Some Example Layout Managers
22
 FlowLayout
 Components placed from left to
right in order added
 When a row is filled, a new row is
started
 Lines can be centered, left-justified
or right-justified (see FlowLayout
constructor)
 See also BoxLayout
 GridLayout
 Components are placed in grid
pattern
 number of rows & columns
specified in constructor
 Grid is filled left-to-right, then top-
to-bottom
 BorderLayout
 Divides window into five areas: North,
South, East, West, Center
 Adding components
 FlowLayout and GridLayout use
container.add(component)
 BorderLayout uses
container.add(component, index)
where index is one of
 BorderLayout.NORTH
 BorderLayout.SOUTH
 BorderLayout.EAST
 BorderLayout.WEST
 BorderLayout.CENTER
FlowLayout Example
23 import javax.swing.*;
import java.awt.*;
public class Statics1 {
public static void main(String[] args) {
new S1GUI();
}
}
class S1GUI {
private JFrame f;
public S1GUI() {
f = new JFrame("Statics1");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 200);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
for (int b = 1; b < 9; b++)
f.add(new JButton("Button " + b));
f.setVisible(true);
}
}
BorderLayout Example
24 import javax.swing.*;
import java.awt.*;
public class Statics2 {
public static void main(String[] args) { new S2GUI(); }
}
class ColoredJPanel extends JPanel {
Color color;
ColoredJPanel(Color color) {
this.color = color;
}
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillRect(0, 0, 400, 400);
}
}
class S2GUI extends JFrame {
public S2GUI() {
setTitle("Statics2");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
add(new ColoredJPanel(Color.RED), BorderLayout.NORTH);
add(new ColoredJPanel(Color.GREEN), BorderLayout.SOUTH);
add(new ColoredJPanel(Color.BLUE), BorderLayout.WEST);
add(new ColoredJPanel(Color.YELLOW), BorderLayout.EAST);
add(new ColoredJPanel(Color.BLACK), BorderLayout.CENTER);
setVisible(true);
}
}
GridLayout Example
25
import javax.swing.*;
import java.awt.*;
public class Statics3 {
public static void main(String[] args) { new S3GUI(); }
}
class S3GUI extends JFrame {
static final int DIM = 25;
static final int SIZE = 12;
static final int GAP = 1;
public S3GUI() {
setTitle("Statics3");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(DIM, DIM, GAP, GAP));
for (int i = 0; i < DIM * DIM; i++) add(new MyPanel());
pack();
setVisible(true);
}
class MyPanel extends JPanel {
MyPanel() { setPreferredSize(new Dimension(SIZE, SIZE)); }
public void paintComponent(Graphics g) {
float gradient =
1f - ((float)Math.abs(getX() - getY()))/(float)((SIZE + GAP) * DIM);
g.setColor(new Color(0f, 0f, gradient));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
More Layout Managers
26
 CardLayout
 Tabbed index card look from
Windows
 GridBagLayout
 Most versatile, but
complicated
 Custom
 Can define your own layout
manager
 But best to try Java's layout
managers first...
 Null
 No layout manager
 Programmer must specify absolute
locations
 Provides great control, but can be
dangerous because of platform
dependency
So what about AWT?
27
 AWT
 Initial GUI toolkit for
Java
 Provided a “Java” look
and feel
 Basic API:
java.awt.*
 Swing was built “on” AWT
 More recent (since Java 1.2) GUI
toolkit
 Added functionality (new
components)
 Supports look and feel for various
platforms (Windows, Mac)
 Basic API: javax.swing.*
 Did Swing replaced AWT?
 Not quite: both use the AWT event
model
Code Examples28
Intro.java
 Button & counter
Basic1.java
 Create a window
Basic2.java
 Create a window using a
constructor
Calculator.java
 Shows use of JOptionPane to
produce standard dialogs
 ComponentExamples.java
 Sample components
 Statics1.java
 FlowLayout example
 Statics2.java
 BorderLayout example
 Statics3.java
 GridLayout example
 LayoutDemo.java
 Multiple layouts

Contenu connexe

Tendances

Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)Bilal Amjad
 
Progress Dialog, AlertDialog, CustomDialog
Progress Dialog, AlertDialog, CustomDialogProgress Dialog, AlertDialog, CustomDialog
Progress Dialog, AlertDialog, CustomDialogSourabh Sahu
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A ReviewFernando Torres
 
Graphical User Interface
Graphical User Interface Graphical User Interface
Graphical User Interface Bivek Pakuwal
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialogKrazy Koder
 
Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activitiesinfo_zybotech
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Muhammad Shebl Farag
 
Spf chapter 03 WinForm
Spf chapter 03 WinFormSpf chapter 03 WinForm
Spf chapter 03 WinFormHock Leng PUAH
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Javasuraj pandey
 
Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4Bhushan Mulmule
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01JONDHLEPOLY
 
IP project for class 12 cbse
IP project for class 12 cbseIP project for class 12 cbse
IP project for class 12 cbsesiddharthjha34
 
Java session10
Java session10Java session10
Java session10Niit Care
 
Gui in matlab :
Gui in matlab :Gui in matlab :
Gui in matlab :elboob2025
 
Windows Forms For Beginners Part - 1
Windows Forms For Beginners Part - 1Windows Forms For Beginners Part - 1
Windows Forms For Beginners Part - 1Bhushan Mulmule
 

Tendances (20)

Java swing
Java swingJava swing
Java swing
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)
 
Progress Dialog, AlertDialog, CustomDialog
Progress Dialog, AlertDialog, CustomDialogProgress Dialog, AlertDialog, CustomDialog
Progress Dialog, AlertDialog, CustomDialog
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
Graphical User Interface
Graphical User Interface Graphical User Interface
Graphical User Interface
 
Java swing
Java swingJava swing
Java swing
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Java
 
21 -windows
21  -windows21  -windows
21 -windows
 
Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activities
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
 
Spf chapter 03 WinForm
Spf chapter 03 WinFormSpf chapter 03 WinForm
Spf chapter 03 WinForm
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Java
 
Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4Windows Forms For Beginners Part - 4
Windows Forms For Beginners Part - 4
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
IP project for class 12 cbse
IP project for class 12 cbseIP project for class 12 cbse
IP project for class 12 cbse
 
Java session10
Java session10Java session10
Java session10
 
Gui in matlab :
Gui in matlab :Gui in matlab :
Gui in matlab :
 
Dsplab v1
Dsplab v1Dsplab v1
Dsplab v1
 
Windows Forms For Beginners Part - 1
Windows Forms For Beginners Part - 1Windows Forms For Beginners Part - 1
Windows Forms For Beginners Part - 1
 

Similaire à L11cs2110sp13

Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.pptTabassumMaktum
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window ToolkitRutvaThakkar1
 
Slot04 creating gui
Slot04 creating guiSlot04 creating gui
Slot04 creating guiViên Mai
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics ProgrammingRiccardo Cardin
 
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdfJEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdfMarlouFelixIIICunana
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Javasuraj pandey
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)Narayana Swamy
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Javayht4ever
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01Ankit Dubey
 
01. introduction to swing
01. introduction to swing01. introduction to swing
01. introduction to swingPrashant Mehta
 
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)Fafadia Tech
 
Computer Programming NC III - Java Swing.pptx
Computer Programming NC III - Java Swing.pptxComputer Programming NC III - Java Swing.pptx
Computer Programming NC III - Java Swing.pptxjonathancapitulo2
 

Similaire à L11cs2110sp13 (20)

Swing
SwingSwing
Swing
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.ppt
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
 
UNIT-2-AJAVA.pdf
UNIT-2-AJAVA.pdfUNIT-2-AJAVA.pdf
UNIT-2-AJAVA.pdf
 
Slot04 creating gui
Slot04 creating guiSlot04 creating gui
Slot04 creating gui
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
Gui
GuiGui
Gui
 
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdfJEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
JEDI Slides-Intro2-Chapter19-Abstract Windowing Toolkit and Swing.pdf
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
 
swings.pptx
swings.pptxswings.pptx
swings.pptx
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
01. introduction to swing
01. introduction to swing01. introduction to swing
01. introduction to swing
 
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
 
Computer Programming NC III - Java Swing.pptx
Computer Programming NC III - Java Swing.pptxComputer Programming NC III - Java Swing.pptx
Computer Programming NC III - Java Swing.pptx
 

Plus de karan saini

Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01karan saini
 
Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)karan saini
 
Snrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofskySnrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofskykaran saini
 
Risc and cisc eugene clewlow
Risc and cisc   eugene clewlowRisc and cisc   eugene clewlow
Risc and cisc eugene clewlowkaran saini
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterationskaran saini
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)karan saini
 
Helen keller-1226880485154369-8
Helen keller-1226880485154369-8Helen keller-1226880485154369-8
Helen keller-1226880485154369-8karan saini
 
Final 121114041321-phpapp01
Final 121114041321-phpapp01Final 121114041321-phpapp01
Final 121114041321-phpapp01karan saini
 
Engh 140118084844-phpapp01
Engh 140118084844-phpapp01Engh 140118084844-phpapp01
Engh 140118084844-phpapp01karan saini
 

Plus de karan saini (20)

Topology ppt
Topology pptTopology ppt
Topology ppt
 
Tibor
TiborTibor
Tibor
 
Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01
 
Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)
 
Snrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofskySnrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofsky
 
Science
ScienceScience
Science
 
Risc and cisc eugene clewlow
Risc and cisc   eugene clewlowRisc and cisc   eugene clewlow
Risc and cisc eugene clewlow
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterations
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
 
Periodic table1
Periodic table1Periodic table1
Periodic table1
 
Maths project
Maths projectMaths project
Maths project
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Lcd monitors
Lcd monitorsLcd monitors
Lcd monitors
 
Lab3
Lab3Lab3
Lab3
 
Helen keller-1226880485154369-8
Helen keller-1226880485154369-8Helen keller-1226880485154369-8
Helen keller-1226880485154369-8
 
Hardware
HardwareHardware
Hardware
 
Gsm cdma1
Gsm cdma1Gsm cdma1
Gsm cdma1
 
Final 121114041321-phpapp01
Final 121114041321-phpapp01Final 121114041321-phpapp01
Final 121114041321-phpapp01
 
Engh 140118084844-phpapp01
Engh 140118084844-phpapp01Engh 140118084844-phpapp01
Engh 140118084844-phpapp01
 

Dernier

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Dernier (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

L11cs2110sp13

  • 1. INTRODUCTION TO GRAPHICAL USER INTERFACES (GUIS) Lecture 10 CS2110 – Fall 2009
  • 2. Announcements 2  A3 will be posted shortly, please start early  Prelim 1: Thursday October 14, Uris Hall G01  We do NOT have any scheduled makeup exam  People with conflicts can take the exam early.  The NORMAL scheduled time is 7:30-9:00  If you have a conflict, take it from 6:00-7:30  Out of town conflicts: you’ll take it during one of these two time periods, supervised by some trustworthy person, who can receive exam/send it back
  • 3. Interactive Programs 3  “Classic” view of computer programs: transform inputs to outputs, stop  Event-driven programs: interactive, long- running  Servers interact with clients  Applications interact with user(s) user user program input events output events input output
  • 4. GUI Motivation Interacting with a program  Program-Driven = Proactive  Statements execute in sequential, predetermined order  Typically use keyboard or file I/O, but program determines when that happens  Usually sing le -thre ade d  Event-Driven = Reactive  Program waits for user input to activate certain statements  Typically uses a GUI (Graphical User Interface)  Often m ulti-thre ade d  Design...Which to pick?  Program called by another program?  Program used at command line?  Program interacts often with user?  Program used in window environment?  How does Java do GUIs? 4
  • 5. Java Support for Building GUIs Java Foundation Classes  Classes for building GUIs  Major components  awt and swing  Pluggable look-and-feel support  Accessibility API  Java 2D API  Drag-and-drop Support  Internationalization  Our main focus: Swing  Building blocks of GUIs  Windows & components  User interactions  Built upon the AWT (Abstract Window Toolkit)  Java event model  Why Swing?  Easier to understand than SWT  Lonnie used SWT in A3 but you don’t actually need to understand the code he wrote 5
  • 6. Swing versus SWT versus AWT  AWT came first  Swing builds on AWT  Strives for total portability  Secretly seems to have a grudge against Windows  Basic architecture is pretty standard  SWT is “new”  Goal is best performance  Great fit with Windows system  Basic architecture is pretty standard 6  We use SWT in A3
  • 7. Java Foundation Classes 7 Pluggable Look-and-Feel Support  Controls look-and-feel for particular windowing environment  E.g., Java, Windows, Mac Accessibility API  Supports assistive technologies such as screen readers and Braille Java 2D  Drawing  Includes rectangles, lines, circles, images, ... Drag-and-drop  Support for drag and drop between Java application and a native application Internationalization  Support for other languages
  • 8. GUI Statics and GUI Dynamics  Components  buttons, labels, lists, sliders, menus, ...  Containers: components that contain other components  frames, panels, dialog boxes, ...  Layout managers: control placement and sizing of components  Events  button-press, mouse-click, key-press, ...  Listeners: an object that responds to an event  Helper classes  Graphics, Color, Font, FontMetrics, Dimension, ... 8 Statics: what’s drawn on the screen Dynamics: user interactions
  • 9. Creating a Window in SWT 9 import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; public class HelloWorld { public static void main(String[] args) { //create the window Display display = new Display(); Shell shell = new Shell(display); Label label = new Label(shell, SWT.NONE); label.setText("Basic Test!"); label.pack(); shell.pack(); shell.open(); // quit Java after closing the window while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose (); } }
  • 10. Creating a Window in Swing 10 import javax.swing.*; public class Basic1 { public static void main(String[] args) { //create the window JFrame f = new JFrame("Basic Test!"); //quit Java after closing the window f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200, 200); //set size in pixels f.setVisible(true); //show the window } }
  • 11. Things to notice  Code style is similar  Both are really “customizing” a prebuilt framework  You write little bits and pieces of software that runs in the context of the preexisting structure  SWT oriented towards somewhat finer control  Swing aims for a sturdy design, but can be harder to customize. 11
  • 12. Creating a Window Using a Constructor 12  import javax.swing.*;  public class Basic2 extends JFrame {  public static void main(String[] args) {  new Basic2();  }  public Basic2() {  setTitle("Basic Test2!"); //set the title  //quit Java after closing the window  setDefaultCloseOperation(EXIT_ON_CLOSE);  setSize(200, 200); //set size in pixels  setVisible(true); //show the window  }  }
  • 13. A More Extensive Example 13  import javax.swing.*;  import java.awt.*;  import java.awt.event.*;  public class Intro extends JFrame {  private int count = 0;  private JButton myButton = new JButton("Push Me!");  private JLabel label = new JLabel("Count: " + count);  public Intro() {  setDefaultCloseOperation(EXIT_ON_CLOSE);  setLayout(new FlowLayout(FlowLayout.LEFT)); //set layout manager  add(myButton); //add components  add(label);  myButton.addActionListener(new ActionListener() {  public void actionPerformed(ActionEvent e) {  count++;  label.setText("Count: " + count);  }  });  pack();  setVisible(true);  }  public static void main(String[] args) {  try {  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());  } catch (Exception exc) {}  new Intro();  }  }
  • 14. GUI Statics 14 Determine which co m po ne nts you want Choose a top-level co ntaine r in which to put the components (JFrame is often a good choice) Choose a layo ut m anag e r to determine how components are arranged Place the components
  • 15. Components = What You See 15  Visual part of an interface  Represents something with position and size  Can be painte d on screen and can receive events  Buttons, labels, lists, sliders, menus, ...  Some windows have hidden components that become visible only when the user takes some action
  • 16. Component Examples 16  import javax.swing.*;  import java.awt.*;  public class ComponentExamples extends JFrame {  public ComponentExamples() {  setLayout(new FlowLayout(FlowLayout.LEFT));  add(new JButton("Button"));  add(new JLabel("Label"));  add(new JComboBox(new String[] { "A", "B", "C" }));  add(new JCheckBox("JCheckBox"));  add(new JSlider(0, 100));  add(new JColorChooser());  setDefaultCloseOperation(EXIT_ON_CLOSE);  pack();  setVisible(true);  }  public static void main(String[] args) {  try {  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());  } catch (Exception exc) {}  new ComponentExamples();  }  }
  • 17. More Components 17 JFileChooser: allows choosing a file JLabel: a simple text label JTextArea: editable text JTextField: editable text (one line) JScrollBar: a scrollbar JPopupMenu: a pop-up menu JProgressBar: a progress bar Lots more!
  • 18. Layout  Issue here concerns the way the components are placed on the screen  If you do it statically (and you can), the resulting application can’t be resized easily  So GUI builders offer a more dynamic option 18
  • 19. Containers 19 A container is a component that  Can hold other components  Has a layout manager Heavyweight vs. lightweight  A heavyweight component interacts directly with the host system  JWindow, JFrame, and JDialog are heavyweight  Except for these top-level containers, Swing components are almost all lightweight  JPanel is lightweight  There are three basic top-level containers  JWindow: top-level window with no border  JFrame: top-level window with border and (optional) menu bar  JDialog: used for dialog windows  Another important container  JPanel: used mostly to organize objects within other containers
  • 20. A Component Tree 20 JFrame JPanel JPanel JPanel JPanel JPanel JPanel JPanel JComboBox (mi) JComboBox (km) JTextField (2000) JSlider JTextField (3226) JSlider JPanelJPanel
  • 21. Layout Managers 21  A layout manager controls placement and sizing of components in a container  If you do not specify a layout manager, the container will use a default:  JPanel default = FlowLayout  JFrame default = BorderLayout  Five common layout managers: BorderLayout, BoxLayout, FlowLayout, GridBagLayout, GridLayout  General syntax container.setLayout(new LayoutMan());  Examples: JPanel p1 = new JPanel(new BorderLayout()); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout());
  • 22. Some Example Layout Managers 22  FlowLayout  Components placed from left to right in order added  When a row is filled, a new row is started  Lines can be centered, left-justified or right-justified (see FlowLayout constructor)  See also BoxLayout  GridLayout  Components are placed in grid pattern  number of rows & columns specified in constructor  Grid is filled left-to-right, then top- to-bottom  BorderLayout  Divides window into five areas: North, South, East, West, Center  Adding components  FlowLayout and GridLayout use container.add(component)  BorderLayout uses container.add(component, index) where index is one of  BorderLayout.NORTH  BorderLayout.SOUTH  BorderLayout.EAST  BorderLayout.WEST  BorderLayout.CENTER
  • 23. FlowLayout Example 23 import javax.swing.*; import java.awt.*; public class Statics1 { public static void main(String[] args) { new S1GUI(); } } class S1GUI { private JFrame f; public S1GUI() { f = new JFrame("Statics1"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(500, 200); f.setLayout(new FlowLayout(FlowLayout.LEFT)); for (int b = 1; b < 9; b++) f.add(new JButton("Button " + b)); f.setVisible(true); } }
  • 24. BorderLayout Example 24 import javax.swing.*; import java.awt.*; public class Statics2 { public static void main(String[] args) { new S2GUI(); } } class ColoredJPanel extends JPanel { Color color; ColoredJPanel(Color color) { this.color = color; } public void paintComponent(Graphics g) { g.setColor(color); g.fillRect(0, 0, 400, 400); } } class S2GUI extends JFrame { public S2GUI() { setTitle("Statics2"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); add(new ColoredJPanel(Color.RED), BorderLayout.NORTH); add(new ColoredJPanel(Color.GREEN), BorderLayout.SOUTH); add(new ColoredJPanel(Color.BLUE), BorderLayout.WEST); add(new ColoredJPanel(Color.YELLOW), BorderLayout.EAST); add(new ColoredJPanel(Color.BLACK), BorderLayout.CENTER); setVisible(true); } }
  • 25. GridLayout Example 25 import javax.swing.*; import java.awt.*; public class Statics3 { public static void main(String[] args) { new S3GUI(); } } class S3GUI extends JFrame { static final int DIM = 25; static final int SIZE = 12; static final int GAP = 1; public S3GUI() { setTitle("Statics3"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new GridLayout(DIM, DIM, GAP, GAP)); for (int i = 0; i < DIM * DIM; i++) add(new MyPanel()); pack(); setVisible(true); } class MyPanel extends JPanel { MyPanel() { setPreferredSize(new Dimension(SIZE, SIZE)); } public void paintComponent(Graphics g) { float gradient = 1f - ((float)Math.abs(getX() - getY()))/(float)((SIZE + GAP) * DIM); g.setColor(new Color(0f, 0f, gradient)); g.fillRect(0, 0, getWidth(), getHeight()); } } }
  • 26. More Layout Managers 26  CardLayout  Tabbed index card look from Windows  GridBagLayout  Most versatile, but complicated  Custom  Can define your own layout manager  But best to try Java's layout managers first...  Null  No layout manager  Programmer must specify absolute locations  Provides great control, but can be dangerous because of platform dependency
  • 27. So what about AWT? 27  AWT  Initial GUI toolkit for Java  Provided a “Java” look and feel  Basic API: java.awt.*  Swing was built “on” AWT  More recent (since Java 1.2) GUI toolkit  Added functionality (new components)  Supports look and feel for various platforms (Windows, Mac)  Basic API: javax.swing.*  Did Swing replaced AWT?  Not quite: both use the AWT event model
  • 28. Code Examples28 Intro.java  Button & counter Basic1.java  Create a window Basic2.java  Create a window using a constructor Calculator.java  Shows use of JOptionPane to produce standard dialogs  ComponentExamples.java  Sample components  Statics1.java  FlowLayout example  Statics2.java  BorderLayout example  Statics3.java  GridLayout example  LayoutDemo.java  Multiple layouts