SlideShare ist ein Scribd-Unternehmen logo
Swing Introduction
2
Introduction to Java Swing
3
AWT vs. Swing
Abstract Windowing Toolkit (AWT)
• Original Java GUI toolkit
• Wrapper API for native GUI components
• Lowest-common denominator for all Java host
environments
Swing
• Implemented entirely in Java on top of AWT
• Richer set of GUI components
• Pluggable look-and-feel support
4
Swing Design Principles
• GUI is built as containment hierarchy of widgets
(i.e. the parent-child nesting relation between
them)
• Event objects and event listeners
– Event object: is created when event occurs (e.g. click),
contains additional info (e.g. mouse coordinates)
– Event listener: object implementing an interface with
an event handler method that gets an event object as
argument
• Separation of Model and View:
– Model: the data that is presented by a widget
– View: the actual presentation on the screen
5
Partial AWT and Swing
Class Hierarchy
java.lang.Object
Component MenuComponent
CheckboxGroup
Button Checkbox
Canvas Choice Container Label List Scrollbar TextComponent
JComponent Window
Frame
JFrame
Dialog
JDialog
Panel
Scrollpane
Applet
JApplet
java.awt.* javax.swing.*
JLabel JList
AbstractButton
JButton
JPanel JScrollpane
6
Swing Widgets (more on this next lecture)
Top-Level Containers
JFrame JPanel
JSplitPane
JTabbedPane
JDialog
JScrollPane
General-Purpose Containers
JButton
JCheckbox JRadioButton
and ButtonGroup
JCombobox
JLabel
JList Menu
7
More Swing Widgets
JColorChooser
JFileChooser
JTree
JTable
8
The Initial Swing GUI
Containment Hierarchy
File Edit
Undo
Redo
Cut
Frame / Dialog / Applet
Root Pane
Layered Pane
Content Pane
Glass Pane
a 3D model
enables menus to
pop up above the
content pane
allows for
interception of
mouse events and
painting across
GUI components
9
The Initial Swing GUI
Containment Hierarchy
aTopLevelContainer:
JFrame or JDialog or JApplet
rootPane:
JRootPane
(JPanel) glassPane:
java.awt.Component
(JPanel) contentPane:
java.awt.Container
layeredPane:
JLayeredPane
menuBar:
JMenuBar
optional
10
Swing Hello World
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World!");
frame.setSize(220, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(null);
JButton button = new JButton("Hello World!");
button.setLocation(30, 30);
button.setSize(150, 100);
contentPane.add(button);
frame.setVisible(true);
}
}
11
Swing Hello World
with Events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Toolkit.getDefaultToolkit().beep();
}
}
...
public class HelloWorld {
public static void main(String[] args) {
...
JButton button = new JButton("Hello World!");
button.addActionListener(new MyActionListener());
...
}
}
12
Containment Hierarchy
of a Menu
…
public class MenuExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JMenu fileMenu = new JMenu("File");
fileMenu.add(new JMenuItem("New"));
fileMenu.add(new JMenuItem("Open"));
fileMenu.add(new JMenuItem("Close"));
JMenu editMenu = new JMenu("Edit");
editMenu.add(new JMenuItem("Undo"));
editMenu.add(new JMenuItem("Redo"));
editMenu.add(new JMenuItem("Cut"));
JMenuBar menubar = new JMenuBar();
menubar.add(fileMenu);
menubar.add(editMenu);
frame.setJMenuBar(menubar);
frame.setVisible(true);
} }
File Edit
Undo
Redo
Cut
File Edit
New
Open
Close
13
Handling Menu Events
...
public class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(MenuExample.frame,
"Got an ActionEvent at " + new Date(e.getWhen())
+ " from " + e.getSource().getClass());
} }
...
public class MenuExample {
static JFrame frame;
public static void main(String[] args) {
...
JMenuItem item = new JMenuItem("Close");
item.addActionListener(new MenuActionListener());
fileMenu.add(item);
...
} }
14
Defining Event Listeners with Anonynous
Classes
• Use new Classname() {…} or new Interfacename(){…} to
create a single object of an anonymous subclass of the given
class/interface
• Anonymous classes can access final variables of their context (i.e.
final variables of the method or class they are created in)
...
public class MenuExample {
public static void main(String[] args) {
final JFrame frame = new JFrame("My Frame");
...
JMenuItem item = new JMenuItem("Close");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showOptionDialog(frame,...
}
});
...
} }
15
Different Kinds of
Swing Events
Low-level events
• MouseEvent: Component got mouse-down, mouse-move, etc.
• KeyEvent: Component got key-press, key-release, etc.
• ComponentEvent: Component resized, moved, etc.
• ContainerEvent: Container's contents changed because a component
was added or removed
• FocusEvent: Component got focus or lost focus
• WindowEvent: Window opened, closed, etc.
High-level semantic events
• ActionEvent: Main action of control invoked (e.g. JButton click)
• AdjustmentEvent: Value was adjusted (e.g. JScrollBar moved)
• ItemEvent: Item was selected or deselected (e.g. in JList)
• TextEvent: Text in component has changed (e.g in JTextField)
16
Events, Listeners, Adapters and
Handler Methods
Event Listener / Adapter Handler Methods
ActionEvent ActionListener actionPerformed
AdjustmentEvent AdjustmentListener adjustmentValueChanged
MouseEvent MouseListener
MouseAdapter
mouseClicked
mouseEntered
mouseExited
mousePressed
mouseReleased
KeyEvent KeyListener
KeyAdapter
keyPressed
keyReleased
keyTyped
ComponentEvent ComponentListener
ComponentAdapter
componentShown
componentHidden
componentMoved
componentResized
Adapter classes with empty methods for Listener interfaces with >1 methods
17
Summary
• Desktop environments consist of:
– Windowing System: handles input/output
– Widget Toolkit:
draws widgets and dispatches their events
– Window Manager: takes care of windows
• Swing is a widget toolkit for Java
– GUI as containment hierarchy of widgets
– Event objects and event listeners
References:
http://java.sun.com/docs/books/tutorial/uiswing/
http://www.javabeginner.com/java-swing-tutorial.htm

Weitere ähnliche Inhalte

Ähnlich wie Swing_Introduction.ppt

event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
Good657694
 
09events
09events09events
09events
Waheed Warraich
 
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
 
swings.pptx
swings.pptxswings.pptx
swings.pptx
Parameshwar Maddela
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
Hemo Chella
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
Hemo Chella
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
Swing
SwingSwing
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Lecture9 oopj
Lecture9 oopjLecture9 oopj
Lecture9 oopj
Dhairya Joshi
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
Arati Gadgil
 
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfpackage net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
sudhirchourasia86
 
Swing
SwingSwing
Swing
Fahim Khan
 
Swing
SwingSwing
Swing
Fahim Khan
 
SWTBot Tutorial
SWTBot TutorialSWTBot Tutorial
SWTBot Tutorial
Chris Aniszczyk
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
udithaisur
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
renuka gavli
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
Adil Mehmoood
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
DrDGayathriDevi
 
State management in android applications
State management in android applicationsState management in android applications
State management in android applications
Gabor Varadi
 

Ähnlich wie Swing_Introduction.ppt (20)

event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
09events
09events09events
09events
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
swings.pptx
swings.pptxswings.pptx
swings.pptx
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Swing
SwingSwing
Swing
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
Lecture9 oopj
Lecture9 oopjLecture9 oopj
Lecture9 oopj
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
 
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfpackage net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
 
Swing
SwingSwing
Swing
 
Swing
SwingSwing
Swing
 
SWTBot Tutorial
SWTBot TutorialSWTBot Tutorial
SWTBot Tutorial
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
State management in android applications
State management in android applicationsState management in android applications
State management in android applications
 

Kürzlich hochgeladen

一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...
IJECEIAES
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 

Kürzlich hochgeladen (20)

一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 

Swing_Introduction.ppt

  • 3. 3 AWT vs. Swing Abstract Windowing Toolkit (AWT) • Original Java GUI toolkit • Wrapper API for native GUI components • Lowest-common denominator for all Java host environments Swing • Implemented entirely in Java on top of AWT • Richer set of GUI components • Pluggable look-and-feel support
  • 4. 4 Swing Design Principles • GUI is built as containment hierarchy of widgets (i.e. the parent-child nesting relation between them) • Event objects and event listeners – Event object: is created when event occurs (e.g. click), contains additional info (e.g. mouse coordinates) – Event listener: object implementing an interface with an event handler method that gets an event object as argument • Separation of Model and View: – Model: the data that is presented by a widget – View: the actual presentation on the screen
  • 5. 5 Partial AWT and Swing Class Hierarchy java.lang.Object Component MenuComponent CheckboxGroup Button Checkbox Canvas Choice Container Label List Scrollbar TextComponent JComponent Window Frame JFrame Dialog JDialog Panel Scrollpane Applet JApplet java.awt.* javax.swing.* JLabel JList AbstractButton JButton JPanel JScrollpane
  • 6. 6 Swing Widgets (more on this next lecture) Top-Level Containers JFrame JPanel JSplitPane JTabbedPane JDialog JScrollPane General-Purpose Containers JButton JCheckbox JRadioButton and ButtonGroup JCombobox JLabel JList Menu
  • 8. 8 The Initial Swing GUI Containment Hierarchy File Edit Undo Redo Cut Frame / Dialog / Applet Root Pane Layered Pane Content Pane Glass Pane a 3D model enables menus to pop up above the content pane allows for interception of mouse events and painting across GUI components
  • 9. 9 The Initial Swing GUI Containment Hierarchy aTopLevelContainer: JFrame or JDialog or JApplet rootPane: JRootPane (JPanel) glassPane: java.awt.Component (JPanel) contentPane: java.awt.Container layeredPane: JLayeredPane menuBar: JMenuBar optional
  • 10. 10 Swing Hello World import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("Hello World!"); frame.setSize(220, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); contentPane.setLayout(null); JButton button = new JButton("Hello World!"); button.setLocation(30, 30); button.setSize(150, 100); contentPane.add(button); frame.setVisible(true); } }
  • 11. 11 Swing Hello World with Events import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { Toolkit.getDefaultToolkit().beep(); } } ... public class HelloWorld { public static void main(String[] args) { ... JButton button = new JButton("Hello World!"); button.addActionListener(new MyActionListener()); ... } }
  • 12. 12 Containment Hierarchy of a Menu … public class MenuExample { public static void main(String[] args) { JFrame frame = new JFrame("My Frame"); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); JMenu fileMenu = new JMenu("File"); fileMenu.add(new JMenuItem("New")); fileMenu.add(new JMenuItem("Open")); fileMenu.add(new JMenuItem("Close")); JMenu editMenu = new JMenu("Edit"); editMenu.add(new JMenuItem("Undo")); editMenu.add(new JMenuItem("Redo")); editMenu.add(new JMenuItem("Cut")); JMenuBar menubar = new JMenuBar(); menubar.add(fileMenu); menubar.add(editMenu); frame.setJMenuBar(menubar); frame.setVisible(true); } } File Edit Undo Redo Cut File Edit New Open Close
  • 13. 13 Handling Menu Events ... public class MenuActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(MenuExample.frame, "Got an ActionEvent at " + new Date(e.getWhen()) + " from " + e.getSource().getClass()); } } ... public class MenuExample { static JFrame frame; public static void main(String[] args) { ... JMenuItem item = new JMenuItem("Close"); item.addActionListener(new MenuActionListener()); fileMenu.add(item); ... } }
  • 14. 14 Defining Event Listeners with Anonynous Classes • Use new Classname() {…} or new Interfacename(){…} to create a single object of an anonymous subclass of the given class/interface • Anonymous classes can access final variables of their context (i.e. final variables of the method or class they are created in) ... public class MenuExample { public static void main(String[] args) { final JFrame frame = new JFrame("My Frame"); ... JMenuItem item = new JMenuItem("Close"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int n = JOptionPane.showOptionDialog(frame,... } }); ... } }
  • 15. 15 Different Kinds of Swing Events Low-level events • MouseEvent: Component got mouse-down, mouse-move, etc. • KeyEvent: Component got key-press, key-release, etc. • ComponentEvent: Component resized, moved, etc. • ContainerEvent: Container's contents changed because a component was added or removed • FocusEvent: Component got focus or lost focus • WindowEvent: Window opened, closed, etc. High-level semantic events • ActionEvent: Main action of control invoked (e.g. JButton click) • AdjustmentEvent: Value was adjusted (e.g. JScrollBar moved) • ItemEvent: Item was selected or deselected (e.g. in JList) • TextEvent: Text in component has changed (e.g in JTextField)
  • 16. 16 Events, Listeners, Adapters and Handler Methods Event Listener / Adapter Handler Methods ActionEvent ActionListener actionPerformed AdjustmentEvent AdjustmentListener adjustmentValueChanged MouseEvent MouseListener MouseAdapter mouseClicked mouseEntered mouseExited mousePressed mouseReleased KeyEvent KeyListener KeyAdapter keyPressed keyReleased keyTyped ComponentEvent ComponentListener ComponentAdapter componentShown componentHidden componentMoved componentResized Adapter classes with empty methods for Listener interfaces with >1 methods
  • 17. 17 Summary • Desktop environments consist of: – Windowing System: handles input/output – Widget Toolkit: draws widgets and dispatches their events – Window Manager: takes care of windows • Swing is a widget toolkit for Java – GUI as containment hierarchy of widgets – Event objects and event listeners References: http://java.sun.com/docs/books/tutorial/uiswing/ http://www.javabeginner.com/java-swing-tutorial.htm