SlideShare a Scribd company logo
Java Programming – Swing
Oum Saokosal
Master’s Degree in information systems,Jeonju
University,South Korea
012 252 752 / 070 252 752
oumsaokosal@gmail.com
Contact Me
• Tel: 012 252 752 / 070 252 752
• Email: oumsaokosal@gmail.com
• FB Page: https://facebook.com/kosalgeek
• PPT: http://www.slideshare.net/oumsaokosal
• YouTube: https://www.youtube.com/user/oumsaokosal
• Twitter: https://twitter.com/okosal
• Web: http://kosalgeek.com
Swing Components
• Swing is a collection of libraries that contains
primitive widgets or controls used for designing
GraphicalUser Interfaces(GUIs).
• Commonly used classes in javax.swing package:
• JButton, JTextBox, JTextArea, JPanel,
JFrame, JMenu, JSlider, JLabel, JIcon, …
• There are many, many such classesto do anything
imaginablewithGUIs
• Here we onlystudy the basic architecture and do
simpleexamples
Swing components, cont.
• Each componentis a Java classwith a fairlyextensive
inheritencyhierarchy:
Object
Component
Container
JComponent
JPanel
Window
Frame
JFrame
Using Swing Components
•Very simple, just create object from
appropriate class – examples:
• JButton but = new JButton();
• JTextField text = new JTextField();
• JTextArea text = new JTextArea();
• JLabel lab = new JLabel();
•Many more classes. Don’t need to know every
one to get started.
Adding components
• Once a component is created, it can be added
to a container by calling the container’s add
method:
Container cp = getContentPane();
cp.add(new JButton(“cancel”));
cp.add(new JButton(“go”));
How these are laid out is determined by the layout
manager.
This is required
Laying out components
•Not so difficult but takes a little practice
•Do not use absolute positioning – not
very portable, does not resize well, etc.
Laying out components
• Use layout managers – basically tells form how
to align components when they’re added.
• Each Container has a layout manager
associated with it.
• A JPanel is a Container– to have different
layout managers associated with different
parts of a form, tile with JPanels and set the
desired layout manager for each JPanel, then
add components directly to panels.
Layout Managers
•Java comes with 7 or 8. Most common
and easiest to use are
• FlowLayout
• BorderLayout
• GridLayout
•Using just these three it is possible to
attain fairly precise layout for most
simple applications.
Setting layout managers
• Very easy to associate a layout manager with a
component. Simply call the setLayout method
on theContainer:
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
As Componentsare added to the container,the layout
manager determinestheir size and positioning.
Event handling
What are events?
• All componentscan listen for one or more events.
• Typical examples are:
• Mouse movements
• Mouse clicks
• Hitting any key
• Hitting return key
• etc.
• Telling the GUI what to do when a particular event
occurs is the role of the event handler.
ActionEvent
• In Java, most components have a special
event called an ActionEvent.
• This is loosely speaking the most common
or canonical event for that component.
• A good example is a click for a button.
• To have any component listen for
ActionEvents, you must register the
component with anActionListener. e.g.
button.addActionListener(new MyAL());
Delegation, cont.
• This is referred to as the Delegation Model.
• When you register an ActionListener with a
component, you must pass it the class
which will handle the event – that is, do the
work when the event is triggered.
• For anActionEvent, this class must
implement the ActionListener interface.
• This is simple a way of guaranteeing that
the actionPerformed method is defined.
actionPerformed
• The actionPerformed method has the following
signature:
void actionPerformed(ActionEvent)
• The object of type ActionEvent passed to the
event handler is used to query information about
the event.
• Some common methods are:
• getSource()
• object reference to component generating event
• getActionCommand()
• some text associated with event (text on button, etc).
actionPerformed, cont.
•These methods are particularly useful
when using one eventhandler for
multiple components.
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
Simplest GUI
import javax.swing.JFrame;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println("main thread continues");
}
}
Another Simple GUI
import javax.swing.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.add(but1);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println("main thread continues");
}
}
Add Layout Manager
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400, 400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton("Click me");
Container cp = getContentPane();//must do this
cp.setLayout(new FlowLayout(FlowLayout.CENTER));
cp.add(but1);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println("main thread continues");
}
}
Add call to event handler
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton("Click me");
Container cp = getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER);
but1.addActionListener(new MyActionListener());
cp.add(but1);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
}
}
Event Handler Code
class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(
"I got clicked",
null
);
}
}
Add second button/event
class SimpleGUI extends JFrame{
SimpleGUI(){
JButton but1 = new Jbutton("Click me");
JButton but2 = new JButton(“exit”);
MyActionListener al = new MyActionListener();
but1.addActionListener(al);
but2.addActionListener(al);
cp.add(but1);
cp.add(but2);
}
}
How to distinguish events –Less
good way
class MyActionListener implents ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getActionCommand().equals("Exit"){
System.exit(1);
}
else if (ae.getActionCommand().equals("Click me"){
JOptionPane.showMessageDialog(null, "I’m clicked");
}
}
}
Good way
class MyActionListener implents ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == but2){
System.exit(1);
}
else if (ae.getSource() == but1){
JOptionPane.showMessageDialog(
null, "I’m clicked");
}
}
Question: How are but1, but2 brought into scope to do this?
Question:Why is this better?

More Related Content

Viewers also liked (20)

PPTX
Android app development - Java Programming for Android
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
PDF
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
OUM SAOKOSAL
 
PPT
Java database connectivity
Vaishali Modi
 
PPTX
Object+oriented+programming+in+java
Ye Win
 
PPT
Measuring And Defining The Experience Of Immersion In Games
OUM SAOKOSAL
 
PPT
Chapter 7 String
OUM SAOKOSAL
 
PPT
ITS (Intelligent Teleportation System)
OUM SAOKOSAL
 
PPT
Terminology In Telecommunication
OUM SAOKOSAL
 
PPT
Chapter 9 Interface
OUM SAOKOSAL
 
PPTX
Tutorial 1
Bible Tang
 
PPT
Kimchi Questionnaire
OUM SAOKOSAL
 
PPT
Actionscript 3 - Session 7 Other Note
OUM SAOKOSAL
 
PPTX
09.1. Android - Local Database (Sqlite)
Oum Saokosal
 
PPT
Chapter 8 Inheritance
OUM SAOKOSAL
 
PPT
Rayleigh Fading Channel In Mobile Digital Communication System
OUM SAOKOSAL
 
PDF
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
Android app development - Java Programming for Android
OUM SAOKOSAL
 
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
OUM SAOKOSAL
 
Java database connectivity
Vaishali Modi
 
Object+oriented+programming+in+java
Ye Win
 
Measuring And Defining The Experience Of Immersion In Games
OUM SAOKOSAL
 
Chapter 7 String
OUM SAOKOSAL
 
ITS (Intelligent Teleportation System)
OUM SAOKOSAL
 
Terminology In Telecommunication
OUM SAOKOSAL
 
Chapter 9 Interface
OUM SAOKOSAL
 
Tutorial 1
Bible Tang
 
Kimchi Questionnaire
OUM SAOKOSAL
 
Actionscript 3 - Session 7 Other Note
OUM SAOKOSAL
 
09.1. Android - Local Database (Sqlite)
Oum Saokosal
 
Chapter 8 Inheritance
OUM SAOKOSAL
 
Rayleigh Fading Channel In Mobile Digital Communication System
OUM SAOKOSAL
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 

Similar to Java OOP Programming language (Part 7) - Swing (20)

PPTX
SWING USING JAVA WITH VARIOUS COMPONENTS
bharathiv53
 
PDF
28-GUI application.pptx.pdf
NguynThiThanhTho
 
PPT
14a-gui.ppt
DrDGayathriDevi
 
PPT
Swing and Graphical User Interface in Java
babak danyal
 
PPTX
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Salini P
 
PPT
13457272.ppt
aptechaligarh
 
PDF
Z blue introduction to gui (39023299)
Narayana Swamy
 
PPT
Graphical User Interface (GUI) - 1
PRN USM
 
PPT
Swing basics
Medi-Caps University
 
PPT
13 gui development
APU
 
PPTX
JAVA (UNIT 5)
Dr. SURBHI SAROHA
 
PPTX
Jp notes
Sreedhar Chowdam
 
PDF
Getting started with GUI programming in Java_1
Muhammad Shebl Farag
 
PDF
Java GUI Programming for beginners-graphics.pdf
PBMaverick
 
PPTX
GUI components in Java
kirupasuchi1996
 
PPTX
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
PPT
Swing and AWT in java
Adil Mehmoood
 
PDF
Swingpre 150616004959-lva1-app6892
renuka gavli
 
SWING USING JAVA WITH VARIOUS COMPONENTS
bharathiv53
 
28-GUI application.pptx.pdf
NguynThiThanhTho
 
14a-gui.ppt
DrDGayathriDevi
 
Swing and Graphical User Interface in Java
babak danyal
 
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
Salini P
 
13457272.ppt
aptechaligarh
 
Z blue introduction to gui (39023299)
Narayana Swamy
 
Graphical User Interface (GUI) - 1
PRN USM
 
Swing basics
Medi-Caps University
 
13 gui development
APU
 
JAVA (UNIT 5)
Dr. SURBHI SAROHA
 
Getting started with GUI programming in Java_1
Muhammad Shebl Farag
 
Java GUI Programming for beginners-graphics.pdf
PBMaverick
 
GUI components in Java
kirupasuchi1996
 
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
Swing and AWT in java
Adil Mehmoood
 
Swingpre 150616004959-lva1-app6892
renuka gavli
 
Ad

More from OUM SAOKOSAL (20)

PPTX
Class Diagram | OOP and Design Patterns by Oum Saokosal
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
PDF
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
PDF
Aggregate rank bringing order to web sites
OUM SAOKOSAL
 
DOC
How to succeed in graduate school
OUM SAOKOSAL
 
PDF
Google
OUM SAOKOSAL
 
PDF
E miner
OUM SAOKOSAL
 
PDF
Data preparation for mining world wide web browsing patterns (1999)
OUM SAOKOSAL
 
PDF
Consumer acceptance of online banking an extension of the technology accepta...
OUM SAOKOSAL
 
DOCX
When Do People Help
OUM SAOKOSAL
 
DOC
Mc Nemar
OUM SAOKOSAL
 
DOCX
Correlation Example
OUM SAOKOSAL
 
DOC
Sem Ski Amos
OUM SAOKOSAL
 
PPT
Sem+Essentials
OUM SAOKOSAL
 
DOC
Path Spss Amos (1)
OUM SAOKOSAL
 
DOC
How To Succeed In Graduate School
OUM SAOKOSAL
 
PPT
Actionscript 3 - Session 4 Core Concept
OUM SAOKOSAL
 
PPT
Actionscript 3 - Session 3 Action Script And Flash
OUM SAOKOSAL
 
PPT
Actionscript 3 - Session 1 Introduction To As 3
OUM SAOKOSAL
 
PPT
Actionscript 3 - Session 5 The Display Api And The Display List
OUM SAOKOSAL
 
Class Diagram | OOP and Design Patterns by Oum Saokosal
OUM SAOKOSAL
 
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
Java OOP Programming language (Part 1) - Introduction to Java
OUM SAOKOSAL
 
Aggregate rank bringing order to web sites
OUM SAOKOSAL
 
How to succeed in graduate school
OUM SAOKOSAL
 
Google
OUM SAOKOSAL
 
E miner
OUM SAOKOSAL
 
Data preparation for mining world wide web browsing patterns (1999)
OUM SAOKOSAL
 
Consumer acceptance of online banking an extension of the technology accepta...
OUM SAOKOSAL
 
When Do People Help
OUM SAOKOSAL
 
Mc Nemar
OUM SAOKOSAL
 
Correlation Example
OUM SAOKOSAL
 
Sem Ski Amos
OUM SAOKOSAL
 
Sem+Essentials
OUM SAOKOSAL
 
Path Spss Amos (1)
OUM SAOKOSAL
 
How To Succeed In Graduate School
OUM SAOKOSAL
 
Actionscript 3 - Session 4 Core Concept
OUM SAOKOSAL
 
Actionscript 3 - Session 3 Action Script And Flash
OUM SAOKOSAL
 
Actionscript 3 - Session 1 Introduction To As 3
OUM SAOKOSAL
 
Actionscript 3 - Session 5 The Display Api And The Display List
OUM SAOKOSAL
 
Ad

Recently uploaded (20)

PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
July Patch Tuesday
Ivanti
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
July Patch Tuesday
Ivanti
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Python basic programing language for automation
DanialHabibi2
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 

Java OOP Programming language (Part 7) - Swing

  • 1. Java Programming – Swing Oum Saokosal Master’s Degree in information systems,Jeonju University,South Korea 012 252 752 / 070 252 752 [email protected]
  • 2. Contact Me • Tel: 012 252 752 / 070 252 752 • Email: [email protected] • FB Page: https://facebook.com/kosalgeek • PPT: http://www.slideshare.net/oumsaokosal • YouTube: https://www.youtube.com/user/oumsaokosal • Twitter: https://twitter.com/okosal • Web: http://kosalgeek.com
  • 3. Swing Components • Swing is a collection of libraries that contains primitive widgets or controls used for designing GraphicalUser Interfaces(GUIs). • Commonly used classes in javax.swing package: • JButton, JTextBox, JTextArea, JPanel, JFrame, JMenu, JSlider, JLabel, JIcon, … • There are many, many such classesto do anything imaginablewithGUIs • Here we onlystudy the basic architecture and do simpleexamples
  • 4. Swing components, cont. • Each componentis a Java classwith a fairlyextensive inheritencyhierarchy: Object Component Container JComponent JPanel Window Frame JFrame
  • 5. Using Swing Components •Very simple, just create object from appropriate class – examples: • JButton but = new JButton(); • JTextField text = new JTextField(); • JTextArea text = new JTextArea(); • JLabel lab = new JLabel(); •Many more classes. Don’t need to know every one to get started.
  • 6. Adding components • Once a component is created, it can be added to a container by calling the container’s add method: Container cp = getContentPane(); cp.add(new JButton(“cancel”)); cp.add(new JButton(“go”)); How these are laid out is determined by the layout manager. This is required
  • 7. Laying out components •Not so difficult but takes a little practice •Do not use absolute positioning – not very portable, does not resize well, etc.
  • 8. Laying out components • Use layout managers – basically tells form how to align components when they’re added. • Each Container has a layout manager associated with it. • A JPanel is a Container– to have different layout managers associated with different parts of a form, tile with JPanels and set the desired layout manager for each JPanel, then add components directly to panels.
  • 9. Layout Managers •Java comes with 7 or 8. Most common and easiest to use are • FlowLayout • BorderLayout • GridLayout •Using just these three it is possible to attain fairly precise layout for most simple applications.
  • 10. Setting layout managers • Very easy to associate a layout manager with a component. Simply call the setLayout method on theContainer: JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout(FlowLayout.LEFT)); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); As Componentsare added to the container,the layout manager determinestheir size and positioning.
  • 12. What are events? • All componentscan listen for one or more events. • Typical examples are: • Mouse movements • Mouse clicks • Hitting any key • Hitting return key • etc. • Telling the GUI what to do when a particular event occurs is the role of the event handler.
  • 13. ActionEvent • In Java, most components have a special event called an ActionEvent. • This is loosely speaking the most common or canonical event for that component. • A good example is a click for a button. • To have any component listen for ActionEvents, you must register the component with anActionListener. e.g. button.addActionListener(new MyAL());
  • 14. Delegation, cont. • This is referred to as the Delegation Model. • When you register an ActionListener with a component, you must pass it the class which will handle the event – that is, do the work when the event is triggered. • For anActionEvent, this class must implement the ActionListener interface. • This is simple a way of guaranteeing that the actionPerformed method is defined.
  • 15. actionPerformed • The actionPerformed method has the following signature: void actionPerformed(ActionEvent) • The object of type ActionEvent passed to the event handler is used to query information about the event. • Some common methods are: • getSource() • object reference to component generating event • getActionCommand() • some text associated with event (text on button, etc).
  • 16. actionPerformed, cont. •These methods are particularly useful when using one eventhandler for multiple components.
  • 23. Simplest GUI import javax.swing.JFrame; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println("main thread continues"); } }
  • 24. Another Simple GUI import javax.swing.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton(“Click me”); Container cp = getContentPane();//must do this cp.add(but1); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println("main thread continues"); } }
  • 25. Add Layout Manager import javax.swing.*; import java.awt.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400, 400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton("Click me"); Container cp = getContentPane();//must do this cp.setLayout(new FlowLayout(FlowLayout.CENTER)); cp.add(but1); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println("main thread continues"); } }
  • 26. Add call to event handler import javax.swing.*; import java.awt.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton("Click me"); Container cp = getContentPane(); cp.setLayout(new FlowLayout(FlowLayout.CENTER); but1.addActionListener(new MyActionListener()); cp.add(but1); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); } }
  • 27. Event Handler Code class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent ae) { JOptionPane.showMessageDialog( "I got clicked", null ); } }
  • 28. Add second button/event class SimpleGUI extends JFrame{ SimpleGUI(){ JButton but1 = new Jbutton("Click me"); JButton but2 = new JButton(“exit”); MyActionListener al = new MyActionListener(); but1.addActionListener(al); but2.addActionListener(al); cp.add(but1); cp.add(but2); } }
  • 29. How to distinguish events –Less good way class MyActionListener implents ActionListener{ public void actionPerformed(ActionEvent ae){ if (ae.getActionCommand().equals("Exit"){ System.exit(1); } else if (ae.getActionCommand().equals("Click me"){ JOptionPane.showMessageDialog(null, "I’m clicked"); } } }
  • 30. Good way class MyActionListener implents ActionListener{ public void actionPerformed(ActionEvent ae){ if (ae.getSource() == but2){ System.exit(1); } else if (ae.getSource() == but1){ JOptionPane.showMessageDialog( null, "I’m clicked"); } } Question: How are but1, but2 brought into scope to do this? Question:Why is this better?