SlideShare a Scribd company logo
1 of 9
Download to read offline
1
JFC / Swing
The Java GUI toolkit
(Reading: The Sun JFC/Swing
Tutorial -- see WWW page)
JFC - Java Foundation Classes
JFC is a GUI toolkit. It is the successor of AWT,
which is the foundation of JFC (usually have to
include AWT with JFC apps).
Swing was the internal development name
Swing replaces ‘heavyweight’ AWT containers with
‘lightweight’ components or widgets.
+ Powerful GUI toolkit: you can do most of what
you want using JFC’s built-in features.
- Complexity: it’s huge!
- Efficiency: it’s slow!
JFC Components
Top-level Containers
Applet Dialog Frame
General-Purpose Containers
Panel Scroll pane
Split pane Tabbed pane
Tool bar
Special-Purpose Containers
Internal frame Layered pane
Root pane
2
JFC Components (2)
Basic Controls
Buttons List Combo box
Menu Slider Text fields
Uneditable Information Displays
Label Progress bar Tool tip
Editable Displays of Formatted Information
Color chooser File chooser
Table Text Tree
Component Features & Attributes
Some features of JFC components/widgets
Borders and layouts can be manipulated.
They understand keyboard/mouse events.
Provide a common style/look-and-feel.
Properties (= resources) can be easily modified.
Support for layout via managers.
Flexible event handling.
Methods to increase efficiency.
A JFC Example
Application that counts the number of button clicks
Let’s look at the design of this application and some
of the code details.
3
Design of the Application
The application consists of:
JFrame (window border)
Content pane (gray rectangle)
JPanel (gray rectangle)
JButton (rectangle & text)
JLabel (text)
JPanel and descendents are
added to the content pane.
JFC Example (1)
import javax.swing.*; //final package name
import java.awt.*; //usually needed.
import java.awt.event.*;
public class SwingApplication {
private static String labelPrefix =
"Number of button clicks: ";
private int Clicks = 0;
JFC Example (2)
public Component createComponents() {
final JLabel label = new
JLabel(labelPrefix + "0 ");
JButton button = new JButton(
"I'm a Swing button!");
button.setMnemonic(KeyEvent.VK_I);
button.addActionListener(new
ActionListener() {
public void
actionPerformed(ActionEvent e){
Clicks++;
label.setText(labelPrefix+Clicks);
}
});
4
JFC Example (3)
// createComponents continued …
label.setLabelFor(button);
// Lay component out on the screen.
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.
createEmptyBorder(30,30,10,30));
pane.setLayout(new GridLayout(0, 1));
pane.add(button);
pane.add(label);
return pane;
}
JFC Example (4)
public static void main(String[] args) {
//Create container and add contents
JFrame frame = new
JFrame("SwingApplication");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
swingApp app = new swingApp();
Component contents =
app.createComponents();
frame.getContentPane().add(contents,
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
Layout Managers
Border Layout
Box Layout
Card Layout
Flow Layout
Grid Layout
Gridbag Layout
5
Swing Features & Concepts
Every time a user presses a key or presses a mouse
button, an event occurs.
Events must be handled. In Swing, this is done by
constructing listeners, which are objects defined to
deal with specific events.
Swing widgets need lots of different listeners. Two
general kinds are very useful.
Action
User clicks a button or chooses a menu item.
User closes a frame (main window)
Listener Type
ActionListener
WindowListener
Event Handling
ActionListener
Used to handle JFC button clicks, menu item
selection, or when a user presses return in a text
field. (Note: this is an interface! You must
implement its actionPerformed method)
WindowListener
User closes a frame (main window)
MouseListener
User presses a mouse button while the cursor is
over a component
Event Handling (2)
MouseMotionListener
User moves the mouse over a component
ComponentListener
Component becomes visible where before it was
not.
FocusListener
Component gets the keyboard focus
ListSelectionListener
Table or list selection changes
6
Implementing an Event Handler
Three bits of code are needed:
In declaration for event handler class, code that
specifies an implementation of a listener
interface, or an extension of such a class.
public class Foo implements ActionListener
Code that registers an instance of the event handler
class as a listener on one or more widgets
myComponent.addActionListener(instanceOfFoo);
Code that implements methods in listener interface:
public void actionPerformed(ActionEvent e) {
//code reacting to the action. }
Suppose we have a single button and we want it to
beep when the user clicks on it.
Here’s a snippet of the event handling code.
public class Beeper ... implements ActionListener {
...
// button is a JButton object.
button.addActionListener(this);
...
public void ActionPerformed(ActionEvent e) {
// make a beeping sound }
Click Me!
Example - Beeping Buttons
Each event is represented by an object: it provides
information about event and identifies the source.
Each event source can have multiple listeners
registered on it. Conversely, a single listener can
register with multiple event sources (and can
handle events from each source).
Hint: When you want to handle events from a
component, first check its how-to section: it
describes how to handle most common events.
event source
event listener
event listener
event listener
event object
Listeners (Single & Multiple)
7
Cartman Rules! Kenny Rules!
Kenny Rules!
Kenny Rules!
Cartman Rules!
Kenny Rules!
Kenny Rules!
Cartman Rules!
Example - Multiple Listeners
Example: two buttons.
Click on left, generate
“Cartman Rules!”
on right, generate
“Kenny Rules!”
Applet has two event sources and two listeners.
One listener listens for events from both buttons.
When it hears an event on either, it adds the button’s
text to the top text area.
The second listener listens for events on right
button. On event, it adds text to the bottom text area.
Example - MultiListeners (2)
Structure of the button event handling code:
public class MultiListener ..implements ActionListener
{ ...
//where initialization occurs:
button1.addActionListener(this);
button2.addActionListener(this);
button2.addActionListener(new Eavesdropper(bottom));
...
public void actionPerformed(ActionEvent e){
top.append(e.getText()+newline); }
}
public class Eavesdropper implements ActionListener {
...
public void actionPerformed(ActionEvent e){
myTextArea.append(e.getText()+newline); }
}
Preview MVC: separate data representation of
Model. JFC provides built-in representations!
Some JFC data models and components that use
them:
If you work with a Swing component, you will want
to work with its underlying data model.
BoundedRangeModel
(JscrollBar,JProgressBar)
ButtonModel (AbstractButton)
ComboBoxModel, MutableComboBoxModel
(JComboBox)
ListModel, ListSelectionModel,
SingleSelectionModel (JList)
TableModel, TableColumnModel (JTable)
TreeModel, TreeSelectionModel (JTree)
Data Models and Components
8
min maxvalue value + extent
extent
Bounded Range Model
Represents an increasing set of values (e.g., a
progress bar).
The data model keeps track of:
upper & lower bound for range.
current value and/or extent
Represents currently selected items in a list
interval selection
element and multiple selection
List Selection Model
index0,index1
index0 index1
index0 index1
last interval
added
Drawing Graphics
Graphics class stores state
current color, font, clipping region, pixel
operation (paint/XOR), translation origin
Primitives:
lines, ovals, polygons, rectangles, round
rectangles, raised/lowered rectangles (‘3d’),
arcs, text, icons (= images)
AWT: paint() method, repaint() to activate
JFC: paintComponent
More advanced graphics in Java 2D API
9
JFC Graphics Example
class ImagePanel extends JPanel {
...
public void paintComponent(Graphics g) {
super.paintComponent(g); //background
g.drawLine(50,50,100,100);
g.setColor(Color.magenta);
g.fill3DRect(10,10,50,50);
g.setColor(Color.black);
g.fillArc(100,10,150,80,0,90);
//draw preloaded image.
g.drawImage(image,200,200,this);
}
}

More Related Content

What's hot

Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical componentsArifa Fatima
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5sotlsoc
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDrRajeshreeKhande
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Javayht4ever
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
Java gui event
Java gui eventJava gui event
Java gui eventSoftNutx
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01JONDHLEPOLY
 
Program klik sederhana
Program klik sederhanaProgram klik sederhana
Program klik sederhanaHenfry Kai
 
Latihan visual basic 2010/Looping/Perulangan
Latihan visual basic 2010/Looping/PerulanganLatihan visual basic 2010/Looping/Perulangan
Latihan visual basic 2010/Looping/PerulanganNurul Arhaiyyu
 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWTbackdoor
 
Flash Prototyping Workbook - Part 1 and 2
Flash Prototyping Workbook - Part 1 and 2Flash Prototyping Workbook - Part 1 and 2
Flash Prototyping Workbook - Part 1 and 2Alexa Andrzejewski
 
Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Mohammed Hussein
 

What's hot (20)

Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical components
 
Lecture8 oopj
Lecture8 oopjLecture8 oopj
Lecture8 oopj
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
Jp notes
Jp notesJp notes
Jp notes
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
GUI Programming with Java
GUI Programming with JavaGUI Programming with Java
GUI Programming with Java
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Java gui event
Java gui eventJava gui event
Java gui event
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
Lenguaje de programación
Lenguaje de programaciónLenguaje de programación
Lenguaje de programación
 
Program klik sederhana
Program klik sederhanaProgram klik sederhana
Program klik sederhana
 
15a gui
15a gui15a gui
15a gui
 
Latihan visual basic 2010/Looping/Perulangan
Latihan visual basic 2010/Looping/PerulanganLatihan visual basic 2010/Looping/Perulangan
Latihan visual basic 2010/Looping/Perulangan
 
H.W 2
H.W 2H.W 2
H.W 2
 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWT
 
Flash Prototyping Workbook - Part 1 and 2
Flash Prototyping Workbook - Part 1 and 2Flash Prototyping Workbook - Part 1 and 2
Flash Prototyping Workbook - Part 1 and 2
 
Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Multimedia lecture ActionScript3
Multimedia lecture ActionScript3
 

Viewers also liked

Why is swing named swing
Why is swing named swingWhy is swing named swing
Why is swing named swingNataraj Dg
 
Tutorial java swing
Tutorial java swingTutorial java swing
Tutorial java swingNataraj Dg
 
13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swingNataraj Dg
 
Comparison between Sense & Sensibility and Pride & Prejudice.
Comparison between Sense & Sensibility and Pride & Prejudice.Comparison between Sense & Sensibility and Pride & Prejudice.
Comparison between Sense & Sensibility and Pride & Prejudice.hitaxidave19
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your BusinessBarry Feldman
 

Viewers also liked (7)

Why is swing named swing
Why is swing named swingWhy is swing named swing
Why is swing named swing
 
Tutorial java swing
Tutorial java swingTutorial java swing
Tutorial java swing
 
13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swing
 
Java lecture
Java lectureJava lecture
Java lecture
 
Comparison between Sense & Sensibility and Pride & Prejudice.
Comparison between Sense & Sensibility and Pride & Prejudice.Comparison between Sense & Sensibility and Pride & Prejudice.
Comparison between Sense & Sensibility and Pride & Prejudice.
 
Java swing
Java swingJava swing
Java swing
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
 

Similar to Swing

Event handling
Event handlingEvent handling
Event handlingswapnac12
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVASrajan Shukla
 
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
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.pptusama537223
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024nehakumari0xf
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024kashyapneha2809
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in JavaAyesha Kanwal
 
Gui builder
Gui builderGui builder
Gui builderlearnt
 
Gui programming a review - mixed content
Gui programming   a review - mixed contentGui programming   a review - mixed content
Gui programming a review - mixed contentYogesh Kumar
 
ACtionlistener in java use in discussion.pptx
ACtionlistener in java use in discussion.pptxACtionlistener in java use in discussion.pptx
ACtionlistener in java use in discussion.pptxMattFlordeliza1
 
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
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingPayal Dungarwal
 
01 Java Is Architecture Neutral
01 Java Is Architecture Neutral01 Java Is Architecture Neutral
01 Java Is Architecture Neutralrajuglobal
 

Similar to Swing (20)

Event handling
Event handlingEvent handling
Event handling
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Java
 
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
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.ppt
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
Gui builder
Gui builderGui builder
Gui builder
 
Gui programming a review - mixed content
Gui programming   a review - mixed contentGui programming   a review - mixed content
Gui programming a review - mixed content
 
Ingles 2do parcial
Ingles   2do parcialIngles   2do parcial
Ingles 2do parcial
 
09events
09events09events
09events
 
ACtionlistener in java use in discussion.pptx
ACtionlistener in java use in discussion.pptxACtionlistener in java use in discussion.pptx
ACtionlistener in java use in discussion.pptx
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
CORE JAVA-2
CORE JAVA-2CORE JAVA-2
CORE JAVA-2
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
01 Java Is Architecture Neutral
01 Java Is Architecture Neutral01 Java Is Architecture Neutral
01 Java Is Architecture Neutral
 

Recently uploaded

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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 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
 

Recently uploaded (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
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...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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 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
 

Swing

  • 1. 1 JFC / Swing The Java GUI toolkit (Reading: The Sun JFC/Swing Tutorial -- see WWW page) JFC - Java Foundation Classes JFC is a GUI toolkit. It is the successor of AWT, which is the foundation of JFC (usually have to include AWT with JFC apps). Swing was the internal development name Swing replaces ‘heavyweight’ AWT containers with ‘lightweight’ components or widgets. + Powerful GUI toolkit: you can do most of what you want using JFC’s built-in features. - Complexity: it’s huge! - Efficiency: it’s slow! JFC Components Top-level Containers Applet Dialog Frame General-Purpose Containers Panel Scroll pane Split pane Tabbed pane Tool bar Special-Purpose Containers Internal frame Layered pane Root pane
  • 2. 2 JFC Components (2) Basic Controls Buttons List Combo box Menu Slider Text fields Uneditable Information Displays Label Progress bar Tool tip Editable Displays of Formatted Information Color chooser File chooser Table Text Tree Component Features & Attributes Some features of JFC components/widgets Borders and layouts can be manipulated. They understand keyboard/mouse events. Provide a common style/look-and-feel. Properties (= resources) can be easily modified. Support for layout via managers. Flexible event handling. Methods to increase efficiency. A JFC Example Application that counts the number of button clicks Let’s look at the design of this application and some of the code details.
  • 3. 3 Design of the Application The application consists of: JFrame (window border) Content pane (gray rectangle) JPanel (gray rectangle) JButton (rectangle & text) JLabel (text) JPanel and descendents are added to the content pane. JFC Example (1) import javax.swing.*; //final package name import java.awt.*; //usually needed. import java.awt.event.*; public class SwingApplication { private static String labelPrefix = "Number of button clicks: "; private int Clicks = 0; JFC Example (2) public Component createComponents() { final JLabel label = new JLabel(labelPrefix + "0 "); JButton button = new JButton( "I'm a Swing button!"); button.setMnemonic(KeyEvent.VK_I); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ Clicks++; label.setText(labelPrefix+Clicks); } });
  • 4. 4 JFC Example (3) // createComponents continued … label.setLabelFor(button); // Lay component out on the screen. JPanel pane = new JPanel(); pane.setBorder(BorderFactory. createEmptyBorder(30,30,10,30)); pane.setLayout(new GridLayout(0, 1)); pane.add(button); pane.add(label); return pane; } JFC Example (4) public static void main(String[] args) { //Create container and add contents JFrame frame = new JFrame("SwingApplication"); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); swingApp app = new swingApp(); Component contents = app.createComponents(); frame.getContentPane().add(contents, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } Layout Managers Border Layout Box Layout Card Layout Flow Layout Grid Layout Gridbag Layout
  • 5. 5 Swing Features & Concepts Every time a user presses a key or presses a mouse button, an event occurs. Events must be handled. In Swing, this is done by constructing listeners, which are objects defined to deal with specific events. Swing widgets need lots of different listeners. Two general kinds are very useful. Action User clicks a button or chooses a menu item. User closes a frame (main window) Listener Type ActionListener WindowListener Event Handling ActionListener Used to handle JFC button clicks, menu item selection, or when a user presses return in a text field. (Note: this is an interface! You must implement its actionPerformed method) WindowListener User closes a frame (main window) MouseListener User presses a mouse button while the cursor is over a component Event Handling (2) MouseMotionListener User moves the mouse over a component ComponentListener Component becomes visible where before it was not. FocusListener Component gets the keyboard focus ListSelectionListener Table or list selection changes
  • 6. 6 Implementing an Event Handler Three bits of code are needed: In declaration for event handler class, code that specifies an implementation of a listener interface, or an extension of such a class. public class Foo implements ActionListener Code that registers an instance of the event handler class as a listener on one or more widgets myComponent.addActionListener(instanceOfFoo); Code that implements methods in listener interface: public void actionPerformed(ActionEvent e) { //code reacting to the action. } Suppose we have a single button and we want it to beep when the user clicks on it. Here’s a snippet of the event handling code. public class Beeper ... implements ActionListener { ... // button is a JButton object. button.addActionListener(this); ... public void ActionPerformed(ActionEvent e) { // make a beeping sound } Click Me! Example - Beeping Buttons Each event is represented by an object: it provides information about event and identifies the source. Each event source can have multiple listeners registered on it. Conversely, a single listener can register with multiple event sources (and can handle events from each source). Hint: When you want to handle events from a component, first check its how-to section: it describes how to handle most common events. event source event listener event listener event listener event object Listeners (Single & Multiple)
  • 7. 7 Cartman Rules! Kenny Rules! Kenny Rules! Kenny Rules! Cartman Rules! Kenny Rules! Kenny Rules! Cartman Rules! Example - Multiple Listeners Example: two buttons. Click on left, generate “Cartman Rules!” on right, generate “Kenny Rules!” Applet has two event sources and two listeners. One listener listens for events from both buttons. When it hears an event on either, it adds the button’s text to the top text area. The second listener listens for events on right button. On event, it adds text to the bottom text area. Example - MultiListeners (2) Structure of the button event handling code: public class MultiListener ..implements ActionListener { ... //where initialization occurs: button1.addActionListener(this); button2.addActionListener(this); button2.addActionListener(new Eavesdropper(bottom)); ... public void actionPerformed(ActionEvent e){ top.append(e.getText()+newline); } } public class Eavesdropper implements ActionListener { ... public void actionPerformed(ActionEvent e){ myTextArea.append(e.getText()+newline); } } Preview MVC: separate data representation of Model. JFC provides built-in representations! Some JFC data models and components that use them: If you work with a Swing component, you will want to work with its underlying data model. BoundedRangeModel (JscrollBar,JProgressBar) ButtonModel (AbstractButton) ComboBoxModel, MutableComboBoxModel (JComboBox) ListModel, ListSelectionModel, SingleSelectionModel (JList) TableModel, TableColumnModel (JTable) TreeModel, TreeSelectionModel (JTree) Data Models and Components
  • 8. 8 min maxvalue value + extent extent Bounded Range Model Represents an increasing set of values (e.g., a progress bar). The data model keeps track of: upper & lower bound for range. current value and/or extent Represents currently selected items in a list interval selection element and multiple selection List Selection Model index0,index1 index0 index1 index0 index1 last interval added Drawing Graphics Graphics class stores state current color, font, clipping region, pixel operation (paint/XOR), translation origin Primitives: lines, ovals, polygons, rectangles, round rectangles, raised/lowered rectangles (‘3d’), arcs, text, icons (= images) AWT: paint() method, repaint() to activate JFC: paintComponent More advanced graphics in Java 2D API
  • 9. 9 JFC Graphics Example class ImagePanel extends JPanel { ... public void paintComponent(Graphics g) { super.paintComponent(g); //background g.drawLine(50,50,100,100); g.setColor(Color.magenta); g.fill3DRect(10,10,50,50); g.setColor(Color.black); g.fillArc(100,10,150,80,0,90); //draw preloaded image. g.drawImage(image,200,200,this); } }