SlideShare a Scribd company logo
1 of 46
Building Graphical User
Interfaces
5.0
2
Overview
• Constructing GUIs
• Interface components
• GUI layout
• Event handling
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
3
GUI Principles
• Components: GUI building blocks.
– Buttons, menus, sliders, etc.
• Layout: arranging components to
form a usable GUI.
– Using layout managers.
• Events: reacting to user input.
– Button presses, menu selections, etc.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
4
AWT and Swing
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
5
Elements of a frame
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Title
Menu bar
Content pane
Window controls
6
Creating a frame
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ImageViewer
{
private JFrame frame;
/**
* Create an ImageViewer show it on screen.
*/
public ImageViewer()
{
makeFrame();
}
// rest of class omitted.
}
7
The content pane
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
/**
* Create the Swing frame and its content.
*/
private void makeFrame()
{
frame = new JFrame("ImageViewer");
Container contentPane = frame.getContentPane();
JLabel label = new JLabel("I am a label.");
contentPane.add(label);
frame.pack();
frame.setVisible(true);
}
8
Adding menus
• JMenuBar
– Displayed below the title.
– Contains the menus.
• JMenu
– e.g. File. Contains the menu items.
• JMenuItem
– e.g. Open. Individual items.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
9Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private void makeMenuBar(JFrame frame)
{
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
// create the File menu
JMenu fileMenu = new JMenu("File");
menubar.add(fileMenu);
JMenuItem openItem = new JMenuItem("Open");
fileMenu.add(openItem);
JMenuItem quitItem = new JMenuItem("Quit");
fileMenu.add(quitItem);
}
10
Event handling
• Events correspond to user interactions with
components.
• Components are associated with different
event types.
– Frames are associated with WindowEvent.
– Menus are associated with ActionEvent.
• Objects can be notified when an event
occurs.
– Such objects are called listeners.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
11
Centralized event receipt
• A single object handles all events.
– Implements the ActionListener interface.
– Defines an actionPerformed method.
• It registers as a listener with each
component.
– item.addActionListener(this)
• It has to work out which component has
dispatched the event.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
12
ActionListener
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public interface ActionListener
{
public void actionPerformed(ActionEvent ev);
}
13Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public class ImageViewer implements ActionListener
{
…
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command.equals("Open")) {
…
}
else if (command.equals("Quit")) {
…
}
…
}
…
private void makeMenuBar(Jframe frame)
{
…
openItem.addActionListener(this);
…
}
}
14
Centralized event handling
• The approach works.
• It is used, so you should be aware of it.
• However …
– It does not scale well.
– Identifying components by their text is fragile.
• An alternative approach is preferred.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
15
Nested class syntax
• Class definitions may be nested.
– public class Enclosing
{
…
private class Inner
{
…
}
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
16
Inner classes
• Instances of the inner class are
localized within the enclosing class.
• Instances of the inner class have
access to the private members of the
enclosing class.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
17
Anonymous inner classes
• Obey the rules of inner classes.
• Used to create one-off objects for
which a class name is not required.
• Use a special syntax.
• The instance is always referenced via
its supertype, as it has no subtype
name.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
18
Anonymous action listener
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
JMenuItem openItem = new JMenuItem("Open");
openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openFile();
}
});
19
Anonymous class elements
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
openItem.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openFile();
}
}
);
Anonymous object creation
Actual parameter
Class definition
20
Exit on window close
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
WindowAdapter provides a no-op
implementation of the
WindowListener interface.
21
The imageviewer project
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
22
Image processing
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
23
Class responsibilities
• ImageViewer
– Sets up the GUI structure.
• ImageFileManager
– Static methods for image file loading and
saving.
• ImagePanel
– Displays the image within the GUI.
• OFImage
– Models a 2D image.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
24
OFImage
• Our subclass of BufferedImage.
• Represents a 2D array of pixels.
• Important methods:
– getPixel, setPixel
– getWidth, getHeight
• Each pixel has a color.
– We use java.awt.Color.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
25
Adding an ImagePanel
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public class ImageViewer
{
private JFrame frame;
private ImagePanel imagePanel;
…
private void makeFrame()
{
Container contentPane = frame.getContentPane();
imagePanel = new ImagePanel();
contentPane.add(imagePanel);
}
…
}
26
Loading an image
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public class ImageViewer
{
private JFrame frame;
private ImagePanel imagePanel;
…
private void openFile()
{
File selectedFile = …;
OFImage image =
ImageFileManager.loadImage(selectedFile);
imagePanel.setImage(image);
frame.pack();
}
…
}
27
Layout managers
• Manage limited space for competing
components.
– FlowLayout, BorderLayout,
GridLayout, BoxLayout,
GridBagLayout.
• Manage Container objects, e.g. a
content pane.
• Each imposes its own style.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
28
FlowLayout
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
29
BorderLayout
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
30
GridLayout
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
31
BoxLayout
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Note: no component
resizing.
32
Nested containers
• Sophisticated layouts can be obtained
by nesting containers.
– Use JPanel as a basic container.
• Each container will have its own
layout manager.
• Often preferable to using a
GridBagLayout.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
33
Struts and Glue
• Invisible components used as spacing.
• Available from the Box class.
• Strut: fixed size.
– Component createHorizontalStrut(int width)
– Component createVerticalStrut(int height)
• Glue: fills available space.
– Component createHorizontalGlue()
– Component createVerticalGlue()
http://docs.oracle.com/javase/tutorial/uiswing/layout/bo
x.html
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
34
Dialogs
• Modal dialogs block all other
interaction.
– Forces a response from the user.
• Non-modal dialogs allow other
interaction.
– This is sometimes desirable.
– May be difficult to avoid inconsistencies.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
35
JOptionPane standard dialogs
• Message dialog
– Message text plus an OK button.
• Confirm dialog
– Yes, No, Cancel options.
• Input dialog
– Message text and an input field.
• Variations are possible.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
36
A message dialog
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private void showAbout()
{
JOptionPane.showMessageDialog(frame,
"ImageViewern" + VERSION,
"About ImageViewer",
JOptionPane.INFORMATION_MESSAGE);
}
37
Image filters
• Functions applied to the whole
image.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int height = getHeight();
int width = getWidth();
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
Color pixel = getPixel(x, y);
alter the pixel's color value;
setPixel(x, y, pixel);
}
}
38
Adding further filters
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private void makeLighter()
{
if(currentImage != null) {
currentImage.lighter();
frame.repaint();
showStatus("Applied: lighter");
}
else {
showStatus("No image loaded.");
}
}
private void threshold()
{
if(currentImage != null) {
currentImage.threshold();
frame.repaint();
showStatus("Applied: threshold");
}
else {
showStatus("No image loaded.");
}
}
Code duplication?
Refactor!
39
Adding further filters
• Define a Filter superclass
(abstract).
• Create function-specific subclasses.
• Create a collection of subclass
instances in ImageViewer.
• Define a generic applyFilter
method.
• See imageviewer2-0.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
40
imageviewer2-0
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
41
Buttons and nested layouts
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
A GridLayout inside
a FlowLayout inside
a BorderLayout.
42
Borders
• Used to add decoration around
components.
• Defined in javax.swing.border
– BevelBorder, CompoundBorder,
EmptyBorder, EtchedBorder,
TitledBorder.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
43
Adding spacing
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
JPanel contentPane = (JPanel)frame.getContentPane();
contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));
// Specify the layout manager with nice spacing
contentPane.setLayout(new BorderLayout(6, 6));
imagePanel = new ImagePanel();
imagePanel.setBorder(new EtchedBorder());
contentPane.add(imagePanel, BorderLayout.CENTER);
44
Other components
• Slider
• Spinner
• Tabbed pane
• Scroll pane
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
45
Review
• Aim for cohesive application structures.
– Endeavor to keep GUI elements separate from
application functionality.
• Pre-defined components simplify creation
of sophisticated GUIs.
• Layout managers handle component
juxtaposition.
– Nest containers for further control.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
46
Review
• Many components recognize user
interactions with them.
• Reactive components deliver events
to listeners.
• Anonymous inner classes are
commonly used to implement
listeners.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

More Related Content

What's hot

Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Jim Driscoll
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemLeonard Axelsson
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Eugene Lazutkin
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of featuresvidyamittal
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Soumen Santra
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?ColdFusionConference
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2Mudasir Syed
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugketan_patel25
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in KotlinExcuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in Kotlinleonsabr
 
Lecture 13, 14 & 15 c# cmd let programming and scripting
Lecture 13, 14 & 15   c# cmd let programming and scriptingLecture 13, 14 & 15   c# cmd let programming and scripting
Lecture 13, 14 & 15 c# cmd let programming and scriptingWiliam Ferraciolli
 
Debugging Your Production JVM
Debugging Your Production JVMDebugging Your Production JVM
Debugging Your Production JVMkensipe
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java BasicsVicter Paul
 

What's hot (20)

Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 
gdfgdfg
gdfgdfggdfgdfg
gdfgdfg
 
04 sorting
04 sorting04 sorting
04 sorting
 
hibernate
hibernatehibernate
hibernate
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy Ecosystem
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of features
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Java 103
Java 103Java 103
Java 103
 
Prototype
PrototypePrototype
Prototype
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in KotlinExcuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in Kotlin
 
Lecture 13, 14 & 15 c# cmd let programming and scripting
Lecture 13, 14 & 15   c# cmd let programming and scriptingLecture 13, 14 & 15   c# cmd let programming and scripting
Lecture 13, 14 & 15 c# cmd let programming and scripting
 
Elementary Sort
Elementary SortElementary Sort
Elementary Sort
 
Debugging Your Production JVM
Debugging Your Production JVMDebugging Your Production JVM
Debugging Your Production JVM
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
 

Similar to Building Graphical User Interfaces (GUIs

Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaGaddafiAdamu1
 
Devcon 2012 Goldweic Nielsen Towards Bboogle 3.0.0 - a Technical Walkthrough
Devcon 2012 Goldweic Nielsen Towards Bboogle 3.0.0 - a Technical WalkthroughDevcon 2012 Goldweic Nielsen Towards Bboogle 3.0.0 - a Technical Walkthrough
Devcon 2012 Goldweic Nielsen Towards Bboogle 3.0.0 - a Technical WalkthroughPatricia Goldweic
 
FIWARE Cloud Exercises (Developer's week)
FIWARE Cloud Exercises (Developer's week)FIWARE Cloud Exercises (Developer's week)
FIWARE Cloud Exercises (Developer's week)Fernando Lopez Aguilar
 
iPhone Programming [7/17] : Behind the Scene
iPhone Programming [7/17] : Behind the SceneiPhone Programming [7/17] : Behind the Scene
iPhone Programming [7/17] : Behind the SceneIMC Institute
 
Introduction to Drupal 7 - Blocks management and contexts
Introduction to Drupal 7 - Blocks management and contextsIntroduction to Drupal 7 - Blocks management and contexts
Introduction to Drupal 7 - Blocks management and contextsKalin Chernev
 
Lightweight Classifications
Lightweight ClassificationsLightweight Classifications
Lightweight ClassificationsESUG
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
Lab 1: Organizing artifacts in folders
Lab 1: Organizing artifacts in foldersLab 1: Organizing artifacts in folders
Lab 1: Organizing artifacts in foldersIBM Rational software
 

Similar to Building Graphical User Interfaces (GUIs (20)

Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) java
 
Javabean1
Javabean1Javabean1
Javabean1
 
javabeans
javabeansjavabeans
javabeans
 
Chapter08
Chapter08Chapter08
Chapter08
 
Chap01
Chap01Chap01
Chap01
 
Java beans
Java beansJava beans
Java beans
 
Devcon 2012 Goldweic Nielsen Towards Bboogle 3.0.0 - a Technical Walkthrough
Devcon 2012 Goldweic Nielsen Towards Bboogle 3.0.0 - a Technical WalkthroughDevcon 2012 Goldweic Nielsen Towards Bboogle 3.0.0 - a Technical Walkthrough
Devcon 2012 Goldweic Nielsen Towards Bboogle 3.0.0 - a Technical Walkthrough
 
FIWARE Cloud Exercises (Developer's week)
FIWARE Cloud Exercises (Developer's week)FIWARE Cloud Exercises (Developer's week)
FIWARE Cloud Exercises (Developer's week)
 
iPhone Programming [7/17] : Behind the Scene
iPhone Programming [7/17] : Behind the SceneiPhone Programming [7/17] : Behind the Scene
iPhone Programming [7/17] : Behind the Scene
 
Extending NetBeans IDE
Extending NetBeans IDEExtending NetBeans IDE
Extending NetBeans IDE
 
Java beans
Java beansJava beans
Java beans
 
Introduction to Drupal 7 - Blocks management and contexts
Introduction to Drupal 7 - Blocks management and contextsIntroduction to Drupal 7 - Blocks management and contexts
Introduction to Drupal 7 - Blocks management and contexts
 
Lightweight Classifications
Lightweight ClassificationsLightweight Classifications
Lightweight Classifications
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Lec02
Lec02Lec02
Lec02
 
Lab 1: Organizing artifacts in folders
Lab 1: Organizing artifacts in foldersLab 1: Organizing artifacts in folders
Lab 1: Organizing artifacts in folders
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Unit4wt
Unit4wtUnit4wt
Unit4wt
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
39
3939
39
 

More from Fajar Baskoro

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxFajar Baskoro
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterFajar Baskoro
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanFajar Baskoro
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUSFajar Baskoro
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxFajar Baskoro
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdfFajar Baskoro
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptxFajar Baskoro
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptxFajar Baskoro
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxFajar Baskoro
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimFajar Baskoro
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahFajar Baskoro
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaFajar Baskoro
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetFajar Baskoro
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdfFajar Baskoro
 

More from Fajar Baskoro (20)

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptx
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarter
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUS
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptx
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptx
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptx
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi Kaltim
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolah
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remaja
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
 
epl1.pdf
epl1.pdfepl1.pdf
epl1.pdf
 
user.docx
user.docxuser.docx
user.docx
 
Dtmart.pptx
Dtmart.pptxDtmart.pptx
Dtmart.pptx
 
DualTrack-2023.pptx
DualTrack-2023.pptxDualTrack-2023.pptx
DualTrack-2023.pptx
 
BADGE.pptx
BADGE.pptxBADGE.pptx
BADGE.pptx
 
womenatwork.pdf
womenatwork.pdfwomenatwork.pdf
womenatwork.pdf
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdf
 

Recently uploaded

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 

Recently uploaded (20)

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 

Building Graphical User Interfaces (GUIs

  • 2. 2 Overview • Constructing GUIs • Interface components • GUI layout • Event handling Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 3. 3 GUI Principles • Components: GUI building blocks. – Buttons, menus, sliders, etc. • Layout: arranging components to form a usable GUI. – Using layout managers. • Events: reacting to user input. – Button presses, menu selections, etc. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 4. 4 AWT and Swing Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 5. 5 Elements of a frame Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Title Menu bar Content pane Window controls
  • 6. 6 Creating a frame Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ImageViewer { private JFrame frame; /** * Create an ImageViewer show it on screen. */ public ImageViewer() { makeFrame(); } // rest of class omitted. }
  • 7. 7 The content pane Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling /** * Create the Swing frame and its content. */ private void makeFrame() { frame = new JFrame("ImageViewer"); Container contentPane = frame.getContentPane(); JLabel label = new JLabel("I am a label."); contentPane.add(label); frame.pack(); frame.setVisible(true); }
  • 8. 8 Adding menus • JMenuBar – Displayed below the title. – Contains the menus. • JMenu – e.g. File. Contains the menu items. • JMenuItem – e.g. Open. Individual items. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 9. 9Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private void makeMenuBar(JFrame frame) { JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); // create the File menu JMenu fileMenu = new JMenu("File"); menubar.add(fileMenu); JMenuItem openItem = new JMenuItem("Open"); fileMenu.add(openItem); JMenuItem quitItem = new JMenuItem("Quit"); fileMenu.add(quitItem); }
  • 10. 10 Event handling • Events correspond to user interactions with components. • Components are associated with different event types. – Frames are associated with WindowEvent. – Menus are associated with ActionEvent. • Objects can be notified when an event occurs. – Such objects are called listeners. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 11. 11 Centralized event receipt • A single object handles all events. – Implements the ActionListener interface. – Defines an actionPerformed method. • It registers as a listener with each component. – item.addActionListener(this) • It has to work out which component has dispatched the event. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 12. 12 ActionListener Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public interface ActionListener { public void actionPerformed(ActionEvent ev); }
  • 13. 13Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class ImageViewer implements ActionListener { … public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if(command.equals("Open")) { … } else if (command.equals("Quit")) { … } … } … private void makeMenuBar(Jframe frame) { … openItem.addActionListener(this); … } }
  • 14. 14 Centralized event handling • The approach works. • It is used, so you should be aware of it. • However … – It does not scale well. – Identifying components by their text is fragile. • An alternative approach is preferred. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 15. 15 Nested class syntax • Class definitions may be nested. – public class Enclosing { … private class Inner { … } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 16. 16 Inner classes • Instances of the inner class are localized within the enclosing class. • Instances of the inner class have access to the private members of the enclosing class. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 17. 17 Anonymous inner classes • Obey the rules of inner classes. • Used to create one-off objects for which a class name is not required. • Use a special syntax. • The instance is always referenced via its supertype, as it has no subtype name. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 18. 18 Anonymous action listener Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling JMenuItem openItem = new JMenuItem("Open"); openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } });
  • 19. 19 Anonymous class elements Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling openItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } } ); Anonymous object creation Actual parameter Class definition
  • 20. 20 Exit on window close Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); WindowAdapter provides a no-op implementation of the WindowListener interface.
  • 21. 21 The imageviewer project Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 22. 22 Image processing Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 23. 23 Class responsibilities • ImageViewer – Sets up the GUI structure. • ImageFileManager – Static methods for image file loading and saving. • ImagePanel – Displays the image within the GUI. • OFImage – Models a 2D image. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 24. 24 OFImage • Our subclass of BufferedImage. • Represents a 2D array of pixels. • Important methods: – getPixel, setPixel – getWidth, getHeight • Each pixel has a color. – We use java.awt.Color. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 25. 25 Adding an ImagePanel Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class ImageViewer { private JFrame frame; private ImagePanel imagePanel; … private void makeFrame() { Container contentPane = frame.getContentPane(); imagePanel = new ImagePanel(); contentPane.add(imagePanel); } … }
  • 26. 26 Loading an image Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class ImageViewer { private JFrame frame; private ImagePanel imagePanel; … private void openFile() { File selectedFile = …; OFImage image = ImageFileManager.loadImage(selectedFile); imagePanel.setImage(image); frame.pack(); } … }
  • 27. 27 Layout managers • Manage limited space for competing components. – FlowLayout, BorderLayout, GridLayout, BoxLayout, GridBagLayout. • Manage Container objects, e.g. a content pane. • Each imposes its own style. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 28. 28 FlowLayout Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 29. 29 BorderLayout Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 30. 30 GridLayout Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 31. 31 BoxLayout Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Note: no component resizing.
  • 32. 32 Nested containers • Sophisticated layouts can be obtained by nesting containers. – Use JPanel as a basic container. • Each container will have its own layout manager. • Often preferable to using a GridBagLayout. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 33. 33 Struts and Glue • Invisible components used as spacing. • Available from the Box class. • Strut: fixed size. – Component createHorizontalStrut(int width) – Component createVerticalStrut(int height) • Glue: fills available space. – Component createHorizontalGlue() – Component createVerticalGlue() http://docs.oracle.com/javase/tutorial/uiswing/layout/bo x.html Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 34. 34 Dialogs • Modal dialogs block all other interaction. – Forces a response from the user. • Non-modal dialogs allow other interaction. – This is sometimes desirable. – May be difficult to avoid inconsistencies. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 35. 35 JOptionPane standard dialogs • Message dialog – Message text plus an OK button. • Confirm dialog – Yes, No, Cancel options. • Input dialog – Message text and an input field. • Variations are possible. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 36. 36 A message dialog Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private void showAbout() { JOptionPane.showMessageDialog(frame, "ImageViewern" + VERSION, "About ImageViewer", JOptionPane.INFORMATION_MESSAGE); }
  • 37. 37 Image filters • Functions applied to the whole image. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling int height = getHeight(); int width = getWidth(); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { Color pixel = getPixel(x, y); alter the pixel's color value; setPixel(x, y, pixel); } }
  • 38. 38 Adding further filters Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private void makeLighter() { if(currentImage != null) { currentImage.lighter(); frame.repaint(); showStatus("Applied: lighter"); } else { showStatus("No image loaded."); } } private void threshold() { if(currentImage != null) { currentImage.threshold(); frame.repaint(); showStatus("Applied: threshold"); } else { showStatus("No image loaded."); } } Code duplication? Refactor!
  • 39. 39 Adding further filters • Define a Filter superclass (abstract). • Create function-specific subclasses. • Create a collection of subclass instances in ImageViewer. • Define a generic applyFilter method. • See imageviewer2-0. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 40. 40 imageviewer2-0 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 41. 41 Buttons and nested layouts Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling A GridLayout inside a FlowLayout inside a BorderLayout.
  • 42. 42 Borders • Used to add decoration around components. • Defined in javax.swing.border – BevelBorder, CompoundBorder, EmptyBorder, EtchedBorder, TitledBorder. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 43. 43 Adding spacing Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setBorder(new EmptyBorder(6, 6, 6, 6)); // Specify the layout manager with nice spacing contentPane.setLayout(new BorderLayout(6, 6)); imagePanel = new ImagePanel(); imagePanel.setBorder(new EtchedBorder()); contentPane.add(imagePanel, BorderLayout.CENTER);
  • 44. 44 Other components • Slider • Spinner • Tabbed pane • Scroll pane Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 45. 45 Review • Aim for cohesive application structures. – Endeavor to keep GUI elements separate from application functionality. • Pre-defined components simplify creation of sophisticated GUIs. • Layout managers handle component juxtaposition. – Nest containers for further control. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 46. 46 Review • Many components recognize user interactions with them. • Reactive components deliver events to listeners. • Anonymous inner classes are commonly used to implement listeners. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Editor's Notes

  1. Replace this with your course title and your name/contact details.